使用基于策略的授权和使用角色授权有什么区别,或者没有区别?
[Authorize(Policy =“ RequiredAdminRole”)]
和
[Authorize(Roles =“ Admin”)]
答案 0 :(得分:1)
对于Role-based authorization,角色通过ClaimsPrincipal类上的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")
的结果。
答案 1 :(得分:0)
基于策略的授权为您提供了更大的灵活性。您可以将自定义授权处理程序与策略一起使用,以添加更复杂的逻辑,而不仅仅是检查用户是否具有特定角色。例如,您的数据库中有一些角色映射。您可以创建一个策略来检查用户是否根据该数据获得了授权,或者可以是任何自定义逻辑。您还可以仅使用.RequireRole("Admin")
创建策略,该策略在技术上与属性[Authorize(Roles = "Admin")]
相同
看看如何在documentation