码迷,mamicode.com
首页 > 其他好文 > 详细

自定义策略-简单实践 <一>

时间:2019-08-10 23:11:25      阅读:250      评论:0      收藏:0      [点我收藏+]

标签:dex   def   completed   cti   ssi   await   username   pass   handler   

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;
        }
    }

 

自定义策略-简单实践 <一>

标签:dex   def   completed   cti   ssi   await   username   pass   handler   

原文地址:https://www.cnblogs.com/qgbo/p/11333352.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!