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


    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)
  • 相关阅读:
    instruments 内存泄漏
    ios常用数学函数
    正则表达式
    view设置成圆角
    关于新浪微博注销后自动登录的问题
    根据视频地址获取某一帧的图像
    使用DES加解密
    实现通讯录的查询与删除
    iOS 动画效果
    iOS 文字下划线
  • 原文地址:https://www.cnblogs.com/qgbo/p/11333352.html
Copyright © 2020-2023  润新知