1.注册策略、使用Claim
services.AddAuthorization(options => { options.AddPolicy("AlbumEdit", policy => { policy.RequireClaim("AlbumEditClaim"); }); }); [Authorize(Policy = "AlbumEdit")]//使用
2.获取用户的Claims:var claims = await _userManager.GetClaimsAsync(user);
3.自定义策略,一个Requirement可以编写多个Handler,多个Handler如果有一个返回了Fail,则策略不满足;如果所有Handler都没有返回Fail,只要有一个Handler返回了Succeed,策略就满足。
using Microsoft.AspNetCore.Authorization; using System.Linq; using System.Threading.Tasks; namespace NetCoreTestMVC2.Auth { /// <summary> /// 策略类 /// </summary> public class EmailRequirement : IAuthorizationRequirement { public string RequiredEmail { get; set; } public EmailRequirement(string requiredEmail) { RequiredEmail = requiredEmail; } } public class EmailHandler : AuthorizationHandler<EmailRequirement> { protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, EmailRequirement requirement) { var claim = context.User.Claims.FirstOrDefault(x => x.Type == "Email"); if (claim != null) { if (claim.Value.EndsWith(requirement.RequiredEmail)) { context.Succeed(requirement); } } return Task.CompletedTask; } } }
//注册自定义策略 Handler
services.AddSingleton<IAuthorizationHandler, EmailHandler>();
4.使用
services.AddAuthorization(options => { //自定义策略 options.AddPolicy("test", policy => { policy.RequireAssertion(context => { if (context.User.HasClaim(x => x.Type == "AlbumEdit")) { return true; } return false; }); }); //自定义策略类 options.AddPolicy("test", policy => { policy.AddRequirements(new EmailRequirement("@qq.com")); }); });
policy.AddRequirements中可以new多个Requirement,必须同时满足所有Requirement才成立。