自定义策略-简单实践 <一>
2019-08-10 22:53 qgbo 阅读(366) 评论(0) 编辑 收藏 举报1.建立 netcore mvc 项目。
2.startup.cs 中添加服务
services.AddAuthorization(option=> { var requirements = new List<MyPermission>(); requirements.Add(new MyPermission() { Url = "/", Name = "admin" }); // 要有 / 开头 requirements.Add(new MyPermission() { Url = "/home/index", Name = "admin" }); requirements.Add(new MyPermission() { Url = "/default", Name = "root" }); option.AddPolicy("qgbplicy", policy => { policy.Requirements.Add(new PermissionRequirement("/denied", requirements, ClaimTypes.Role)); }); }).AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie( option => { option.AccessDeniedPath = "/home/Denied"; option.LoginPath = "/home/Login"; } ); services.AddSingleton<IAuthorizationHandler, PermissionHandler>();
app.UseAuthentication();
3.登录的controller:
[AllowAnonymous] [HttpPost] public async Task<IActionResult> Login(string userName, string password, string returnUrl = null) { //用户标识 var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme); //如果是基于角色的授权策略,这里要添加用户 identity.AddClaim(new Claim(ClaimTypes.Name, "gsw")); //如果是基于角色的授权策略,这里要添加角色 identity.AddClaim(new Claim(ClaimTypes.Role, "admin")); await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity)); if (returnUrl == null) { returnUrl = TempData["returnUrl"]?.ToString(); } if (returnUrl != null) { return Redirect(returnUrl); } else { return RedirectToAction(nameof(HomeController.Index), "Home"); } }
4.创建 PermissionHandler 类
public class PermissionHandler : AuthorizationHandler<PermissionRequirement> { protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionRequirement requirement) { //从AuthorizationHandlerContext转成HttpContext,以便取出表求信息 var httpContext = (context.Resource as Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext).HttpContext; //是否经过验证 if (httpContext.User.Identity.IsAuthenticated) { var questUrl = httpContext.Request.Path.Value.ToLower(); //权限中是否存在请求的url if (requirement.Permissions.Any(w => w.Url.ToLower() == questUrl)) { var name = httpContext.User.Claims.SingleOrDefault(s => s.Type == requirement.ClaimType).Value; //验证权限 if (requirement.Permissions.Any(w => w.Name == name)) { context.Succeed(requirement); } else { //无权限跳转到拒绝页面 httpContext.Response.Redirect(requirement.DeniedAction); } } else { context.Succeed(requirement); } } return Task.CompletedTask; } }
气功波(18037675651)