基于策略的授权与在.Net Core中的角色进行授权 [英] Policy-based authorization vs authorize with role in .Net Core
问题描述
使用基于策略的授权与使用角色授权有什么区别,或者没有区别?
What is the difference between using policy-based authorization and authorize with role, or there is no difference?
[Authorize(Policy ="RequiredAdminRole")]
[Authorize(Policy = "RequiredAdminRole")]
和
[Authorize(Roles ="Admin")]
[Authorize(Roles = "Admin")]
推荐答案
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"));
}
来自 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")
的结果.
You can see that the policy is just to check the result of context.User.IsInRole("Admin")
.
这篇关于基于策略的授权与在.Net Core中的角色进行授权的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!