基于策略的授权与.Net Core 中的角色授权

Policy-based authorization vs authorize with role in .Net Core

使用policy-based授权和authorize with role有什么区别,还是没有区别?

[Authorize(Policy = "RequiredAdminRole")]

[Authorize(Roles = "Admin")]

基于策略的授权给你更多的灵活性。您可以使用带有策略的自定义授权处理程序来添加比仅检查您的用户是否具有特定角色更复杂的逻辑。例如,您的数据库中有一些角色映射。您可以创建一个策略来检查您的用户是否根据该数据获得授权,或者可以是任何自定义逻辑。您还可以仅使用 .RequireRole("Admin") 创建策略,从技术上讲,这与属性 [Authorize(Roles = "Admin")] 的作用相同 看看如何在 documentation

中实现自定义授权处理程序

对于 Role-based authorization,角色通过 ClaimsPrincipal class.

上的 IsInRole 方法公开给开发人员

在我看来,如果您的意思是将策略配置为

,则没有区别
services.AddAuthorization(options =>
          options.AddPolicy("RequiredAdminRole",
          policy => policy.RequireRole("Admin"));
        }

来自RequireRole

public AuthorizationPolicyBuilder RequireRole(IEnumerable<string> roles)
    {
        if (roles == null)
        {
            throw new ArgumentNullException(nameof(roles));
        }

        Requirements.Add(new RolesAuthorizationRequirement(roles));
        return this;
    }

RolesAuthorizationRequirement

public IEnumerable<string> AllowedRoles { get; }

    /// <summary>
    /// Makes a decision if authorization is allowed based on a specific requirement.
    /// </summary>
    /// <param name="context">The authorization context.</param>
    /// <param name="requirement">The requirement to evaluate.</param>

    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, RolesAuthorizationRequirement requirement)
    {
        if (context.User != null)
        {
            bool found = false;
            if (requirement.AllowedRoles == null || !requirement.AllowedRoles.Any())
            {
                // Review: What do we want to do here?  No roles requested is auto success?
            }
            else
            {
                found = requirement.AllowedRoles.Any(r => context.User.IsInRole(r));
            }
            if (found)
            {
                context.Succeed(requirement);
            }
        }
        return Task.CompletedTask;
    }

可以看到策略只是检查context.User.IsInRole("Admin")的结果。