在下面的控制器代码中,只有处于“管理员”角色的用户才能访问GetData()操作方法, 因为控制器级别Authorizeattribute。 但我也希望只有“经理”角色的用户能够访问GetData()动作方法,如何编写 这个的自定义属性?
[Authorize(Roles = "Administrator")]
Pulic class AdminController : Controller
{
[Authorize(Roles = "Administrator, Manager")]
public IActionResult GetData()
{
}
}
答案 0 :(得分:2)
始终首先检查类级属性,因此它会拒绝任何不正确角色的人。您需要在类级别指定最宽的访问权限,然后在需要的方法级别缩小范围:
unknown error: cannot get automation extension
from unknown error: page could not be found: chrome-extension://aapnijgdinlhnhlmodcfapnahmbfebeb/_generated_background_page.html
(Session info: headless chrome=59.0.3071.115)
(Driver info: chromedriver=2.31.488774 (7e15618d1bf16df8bf0ecf2914ed1964a387ba0b),platform=Mac OS X 10.12.3 x86_64) (Selenium::WebDriver::Error::UnknownError)
答案 1 :(得分:0)
在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)
{
}
}
然后,按如下方式装饰控制器和动作方法:
[Authorize(Policy = "Administrator")]
Public class AdminController : Controller
{
public IActionResult GetData()
{
}
[Authorize(Policy = "AdminManager")]
public IActionResult AdministratorOnly()
{
}
}