Visual
一句话的事儿
- 使用Claims
- 自定义 Policy
- RequireAssertion
- AddRequirements
Policy 内置的方式
- RequireAuthenticatedUser —>必须是登录用户
- RequireClaim —>要求特定的Claim出现,并且对应的值也是特定的值
- RequireRole —>要求是特定的角色
- RequireUserName —>特定的用户名
Policy 自定义
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
EmailRequirement:
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()));