问题
What is the difference between using policy-based authorization and authorize with role, or there is no difference?
[Authorize(Policy = "RequiredAdminRole")]
and
[Authorize(Roles = "Admin")]
回答1:
For Role-based authorization , Roles are exposed to the developer through the IsInRole method on the ClaimsPrincipal class.
In my opinion,there is no difference if you mean the Policy is configured as
services.AddAuthorization(options =>
options.AddPolicy("RequiredAdminRole",
policy => policy.RequireRole("Admin"));
}
From RequireRole:
public AuthorizationPolicyBuilder RequireRole(IEnumerable<string> roles)
{
if (roles == null)
{
throw new ArgumentNullException(nameof(roles));
}
Requirements.Add(new RolesAuthorizationRequirement(roles));
return this;
}
and 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;
}
You can see that the policy is just to check the result of context.User.IsInRole("Admin")
.
回答2:
Policy based authorization gives you more flexibility. You can use custom authorization handlers with policies to add more complex logic than just checking if your user has specific role. For example you have some roles mappings in you database. You can create a policy that will check if your user is authorized according to that data or that can be any custom logic. You can also create policy only with .RequireRole("Admin")
which technically will do the same as an attribute [Authorize(Roles = "Admin")]
Take a look how to implement custom authorization handlers in documentation
来源:https://stackoverflow.com/questions/58464970/policy-based-authorization-vs-authorize-with-role-in-net-core