假如有这么一种授权需求。
- 须拥有管理员(Admin)角色
- 并且包含“Edit Role”声明,且值为 true
- 但用户只要拥有“Super Admin”角色也可以进行编辑
❌ 错误写法:
services.AddAuthorization(options =>
{
options.AddPolicy("EditRolePolicy", policy => policy
.RequireRole("Admin")
.RequireClaim("Edit Role", "true")
.RequireRole("Super Admin")
);
});
✅ 使用委托创建自定义策略授权的正确写法:
services.AddAuthorization(options =>
{
options.AddPolicy("EditRolePolicy",
policy => policy.RequireAssertion(context =>
context.User.IsInRole("Admin") && context.User.HasClaim(claim => claim.Type == "Edit Role" && claim.Value == "true") ||
context.User.IsInRole("Super Admin")));
});
封装代码:
public void ConfigureServices(IServiceCollection services)
{
...
// 使用声明式授权
services.AddAuthorization(options =>
{
options.AddPolicy("EditRolePolicy", policy => policy.RequireAssertion(AuthorizeAccess));
});
...
}
// 授权访问
private bool AuthorizeAccess(AuthorizationHandlerContext context)
{
return context.User.IsInRole("Admin") && context.User.HasClaim(claim => claim.Type == "Edit Role" && claim.Value == "true") ||
context.User.IsInRole("Super Admin");
}
只有 Admin 权限的 zhangsan,无法编辑角色:
Admin + Edit Role 为 true 的 ltm:
有了 Super Admin 权限后的 zhangsan: