在下面的 Controller 代码中,由于 Controller 级别的GetData()
,只有具有“管理员”角色的用户才能访问AuthorizeAttribute
操作方法。但我也希望仅具有“管理员”角色的用户可以访问GetData()
操作方法。
[Authorize(Roles = "Administrator")]
Public class AdminController : Controller
{
[Authorize(Roles = "Administrator, Manager")]
public IActionResult GetData()
{
}
}
.NET Core框架中是否提供诸如OverrideAuthorization属性之类的选项来满足此要求?
最佳答案
经过对授权程序集进行长时间分析之后,便能够找到解决方案。
在startup.cs文件中,添加“授权”,如下所示:
services.AddAuthorization(options =>
{
var roles = new List<string>{ Role.Administrator, Role.Manager};
var requirement =
new List<IAuthorizationRequirement> {new AdminManagerAuthorizationOverrideOthers(roles) };
var sharedAuthentication =
new AuthorizationPolicy(requirement,
new List<string>());
options.AddPolicy(name: "AdminManager", policy: sharedAuthentication);
options.AddPolicy(name: "Administrator", configurePolicy: policy => policy.RequireAssertion(e =>
{
if (e.Resource is AuthorizationFilterContext afc)
{
var noPolicy = afc.Filters.OfType<AuthorizeFilter>().Any(p =>
p.Policy.Requirements.Count == 1 &&
p.Policy.Requirements.Single() is AdminManagerAuthorizationOverrideOthers);
if (noPolicy)
return true;
}
return e.User.IsInRole(Role.Administrator);
}));
});
在从“Microsoft.AspNetCore.Authorization.Infrastructure”命名空间继承“RolesAuthorizationRequirement”的任何命名空间中创建一个类,如下所示:
public class AdminManagerAuthorizationOverrideOthers : RolesAuthorizationRequirement
{
public AdminManagerAuthorizationOverrideOthers(IEnumerable<string> allowedRoles) : base(allowedRoles)
{
}
}
然后,如下装饰 Controller 和操作方法:
[Authorize(Policy = "Administrator")]
Public class AdminController : Controller
{
public IActionResult GetData()
{
}
[Authorize(Policy = "AdminManager")]
public IActionResult AdministratorOnly()
{
}
}
关于c# - .NETCore中的OverrideAuthorization属性,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47571426/