Policy 内置的方式
- RequireAuthenticatedUser
- RequireClaim
- RequireRole
-
Policy 自定义
RequireAssertion
services.AddAuthorization(options =>
{
options.AddPolicy("仅限管理员", policy => policy.RequireRole("Administrators"));
options.AddPolicy("编辑专辑", policy => policy.RequireClaim("Edit Albums"));
options.AddPolicy("编辑专辑1", policy => policy.RequireAssertion(context =>
{
return context.User.HasClaim(c => c.Type == "Edit Albums");
}));
});
AddRequirements
IAuthorizationRequirement
- AuthorizationHandler
- AuthorizationHandler
- …(一个 Requirement 可以有多个 Handler)
- 如果一个 Handler 返回 Succeed,而其他的都没有返回 Fail,那么这个 Requirement 就被满足了
- AuthorizationHandler
using Microsoft.AspNetCore.Authorization;
namespace Heavy.Web.Auth
{
public class EmailRequirement : IAuthorizationRequirement
{
public string RequiredEmail { get; set; }
public EmailRequirement(string requiredEmail)
{
RequiredEmail = requiredEmail;
}
}
}
EmailHandler:
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
namespace Heavy.Web.Auth
{
public class EmailHandler : AuthorizationHandler<EmailRequirement>
{
protected override Task HandleRequirementAsync(
AuthorizationHandlerContext context,
EmailRequirement requirement)
{
var claim = context.User.Claims.FirstOrDefault(c => c.Type == "Email");
if (claim != null && claim.Value.EndsWith(requirement.RequiredEmail))
{
context.Succeed(requirement);
}
return Task.CompletedTask;
}
}
}
配置 Requirement:
services.AddAuthorization(options =>
{
options.AddPolicy("仅限管理员", policy => policy.RequireRole("Administrators"));
options.AddPolicy("编辑专辑", policy => policy.RequireClaim("Edit Albums"));
//options.AddPolicy("编辑专辑1", policy => policy.RequireClaim("Edit Albums", new List<string> { "123", "456", "789" }));
options.AddPolicy("编辑专辑1", policy => policy.RequireAssertion(context =>
{
return context.User.HasClaim(c => c.Type == "Edit Albums");
}));
options.AddPolicy("编辑专辑2", policy => policy.AddRequirements(
new EmailRequirement("@126.com")));
});
// 注册 Handler
services.AddSingleton<IAuthorizationHandler, EmailHandler>();
一个 Policy 里面的多个 Requirement 必须都满足才能通过:
options.AddPolicy("编辑专辑2", policy => policy.AddRequirements(
new EmailRequirement("@126.com"),
new QualifiedUserRequirement()));