///第一步:配置鉴权的服务 services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(options => { options.LoginPath = new PathString("/Members/Login"); //如果授权失败,就跳转到这个路径去中 options.AccessDeniedPath = new PathString("/Members/Login");//authorize 登录了 权限不够跳这个地址, });//用cookie
下面是策略
//策略认证 services.AddAuthorization(options => { options.AddPolicy("jspPolicy", polic => { polic.AddRequirements(new CustomAuthorizationRequirement("jspPolicy")); }); }); }
第二步 配置UseAuthentication鉴权 在UseRouting 和UseAuthorization 中间
第三部 登录 的控制器
[HttpPost] public async Task<IActionResult> Login(CurrentUserViewModel viewModel) { string verifyCode = base.HttpContext.Session.GetString("CheckCode"); if (verifyCode != null && verifyCode.Equals(viewModel.verify, StringComparison.CurrentCultureIgnoreCase)) { #region 这里在实际开发中是-链接数据库做数据校验 这里简单验证一下 if (viewModel.Name=="abc"&&(viewModel.Password=="abc")) { #region 鉴权:鉴权,检测有没有登录,登录的是谁,赋值给User //rolelist 是登录成功后用户的角色---是来自于数据库的查询;不同的用户会查询出不同的角色; var rolelist = new List<string>() { //来自于数库的查询 "Admin", "Teacher", "Student" }; //ClaimTypes.Role就是做权限认证的标识; var claims = new List<Claim>()//鉴别你是谁,相关信息 { new Claim(ClaimTypes.Role,"Admin"), new Claim(ClaimTypes.Name,viewModel.Name), new Claim("Password",viewModel.Password),//可以写入任意数据 new Claim("Account","Administrator"), new Claim("role","admin"), new Claim("chen","chen"), new Claim("xiao","xiao") }; foreach (var role in rolelist) { claims.Add(new Claim(ClaimTypes.Role, role)); } ClaimsPrincipal userPrincipal = new ClaimsPrincipal(new ClaimsIdentity(claims, "Customer")); HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, userPrincipal, new AuthenticationProperties { ExpiresUtc = DateTime.UtcNow.AddMinutes(30),//过期时间:30分钟 }).Wait(); #endregion var user = HttpContext.User; return base.Redirect("/Home/Index"); } else { base.ViewBag.Msg = "账号密码错误"; } #endregion } else { base.ViewBag.Msg = "验证码错误"; } return View(); }
第四部分 定义策略的名称 继承IAuthorizationRequirement 接口
public class CustomAuthorizationRequirement: IAuthorizationRequirement { public CustomAuthorizationRequirement(string policyname) { this.Name = policyname; } public string Name { get; set; } }
第五部门 真正处理策略的方法CustomAuthorizationHandler
/// <summary> /// 具体策略的执行 /// </summary> public class CustomAuthorizationHandler: AuthorizationHandler<CustomAuthorizationRequirement> { protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, CustomAuthorizationRequirement requirement) { if (requirement.Name == "jspPolicy") { ///策略1的逻辑 if (true) { //这里处理你自己的 业务逻辑 通过了 context.Succeed(requirement); //验证通过了 } }else if(requirement.Name == "cutomPolicy")
{
///可以多个策略
}
return Task.CompletedTask; //验证不同过 } }
第六部 别忘记ioc 注册 我还是用上次autofac
public static void RegsterType(this ContainerBuilder builder) { builder.RegisterType<test>().As<Itest>(); builder.RegisterType<CustomAuthorizationHandler>().As<IAuthorizationHandler>(); builder.RegisterType<World>().As<IWorld>().PropertiesAutowired(new CustomPropertySelector()); }
第七步骤验证
[Authorize(policy: "jspPolicy")] public IActionResult Privacy() { _world.aa(); return View(); }