现在我像这样装饰一个方法,以允许“成员”访问我的控制器动作
[Authorize(Roles="members")]
如何允许多个角色?例如,下面的不工作,但它显示了我正在尝试做什么(允许“成员”和“管理员”访问):
[Authorize(Roles="members", "admin")]
现在我像这样装饰一个方法,以允许“成员”访问我的控制器动作
[Authorize(Roles="members")]
如何允许多个角色?例如,下面的不工作,但它显示了我正在尝试做什么(允许“成员”和“管理员”访问):
[Authorize(Roles="members", "admin")]
当前回答
如果你想使用自定义角色,你可以这样做:
CustomRoles类:
public static class CustomRoles
{
public const string Administrator = "Administrador";
public const string User = "Usuario";
}
使用
[Authorize(Roles = CustomRoles.Administrator +","+ CustomRoles.User)]
如果你的角色很少,也许你可以把它们结合起来(为了清晰起见):
public static class CustomRoles
{
public const string Administrator = "Administrador";
public const string User = "Usuario";
public const string AdministratorOrUser = Administrator + "," + User;
}
使用
[Authorize(Roles = CustomRoles.AdministratorOrUser)]
其他回答
如果你想使用自定义角色,你可以这样做:
CustomRoles类:
public static class CustomRoles
{
public const string Administrator = "Administrador";
public const string User = "Usuario";
}
使用
[Authorize(Roles = CustomRoles.Administrator +","+ CustomRoles.User)]
如果你的角色很少,也许你可以把它们结合起来(为了清晰起见):
public static class CustomRoles
{
public const string Administrator = "Administrador";
public const string User = "Usuario";
public const string AdministratorOrUser = Administrator + "," + User;
}
使用
[Authorize(Roles = CustomRoles.AdministratorOrUser)]
您可以使用授权策略 在Startup.cs
services.AddAuthorization(options =>
{
options.AddPolicy("admin", policy => policy.RequireRole("SuperAdmin","Admin"));
options.AddPolicy("teacher", policy => policy.RequireRole("SuperAdmin", "Admin", "Teacher"));
});
在控制器文件中:
[Authorize(Policy = "teacher")]
[HttpGet("stats/{id}")]
public async Task<IActionResult> getStudentStats(int id)
{ ... }
“教师”政策接受3个角色。
另一个清晰的解决方案是使用常量来保持约定,并添加多个[Authorize]属性。看看这个:
public static class RolesConvention
{
public const string Administrator = "Administrator";
public const string Guest = "Guest";
}
然后在控制器中:
[Authorize(Roles = RolesConvention.Administrator )]
[Authorize(Roles = RolesConvention.Guest)]
[Produces("application/json")]
[Route("api/[controller]")]
public class MyController : Controller
使用AspNetCore 2。X,你必须走不同的路:
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
public class AuthorizeRoleAttribute : AuthorizeAttribute
{
public AuthorizeRoleAttribute(params YourEnum[] roles)
{
Policy = string.Join(",", roles.Select(r => r.GetDescription()));
}
}
就像这样使用它:
[Authorize(YourEnum.Role1, YourEnum.Role2)]
另一种选择是使用一个单独的授权过滤器,但删除内部报价。
[Authorize(Roles="members,admin")]