假如有这么一种授权需求。

    • 须拥有管理员(Admin)角色
      • 并且包含“Edit Role”声明,且值为 true
    • 但用户只要拥有“Super Admin”角色也可以进行编辑

    ❌ 错误写法:

    1. services.AddAuthorization(options =>
    2. {
    3. options.AddPolicy("EditRolePolicy", policy => policy
    4. .RequireRole("Admin")
    5. .RequireClaim("Edit Role", "true")
    6. .RequireRole("Super Admin")
    7. );
    8. });

    ✅ 使用委托创建自定义策略授权的正确写法:

    1. services.AddAuthorization(options =>
    2. {
    3. options.AddPolicy("EditRolePolicy",
    4. policy => policy.RequireAssertion(context =>
    5. context.User.IsInRole("Admin") && context.User.HasClaim(claim => claim.Type == "Edit Role" && claim.Value == "true") ||
    6. context.User.IsInRole("Super Admin")));
    7. });

    封装代码:

    1. public void ConfigureServices(IServiceCollection services)
    2. {
    3. ...
    4. // 使用声明式授权
    5. services.AddAuthorization(options =>
    6. {
    7. options.AddPolicy("EditRolePolicy", policy => policy.RequireAssertion(AuthorizeAccess));
    8. });
    9. ...
    10. }
    11. // 授权访问
    12. private bool AuthorizeAccess(AuthorizationHandlerContext context)
    13. {
    14. return context.User.IsInRole("Admin") && context.User.HasClaim(claim => claim.Type == "Edit Role" && claim.Value == "true") ||
    15. context.User.IsInRole("Super Admin");
    16. }

    只有 Admin 权限的 zhangsan,无法编辑角色:
    image.png
    Admin + Edit Role 为 true 的 ltm:
    image.png

    有了 Super Admin 权限后的 zhangsan:
    image.png