我有一个 Controller ,我希望有两个角色能够访问它。 1 位管理员或 2 位版主
我知道你可以做 [Authorize(Roles="admin, moderators")] 但我在枚举中有我的角色。使用枚举我只能授权一个角色。我不知道如何授权两个。
我尝试过类似 [Authorize(Roles=MyEnum.Admin, MyEnum.Moderator)] 的方法,但无法编译。
曾经有人这样建议:
[Authorize(Roles=MyEnum.Admin)]
[Authorize(MyEnum.Moderator)]
public ActionResult myAction()
{
}
但它不能作为 OR 工作。我认为在这种情况下,用户必须同时成为两个角色的一部分。我是否忽略了一些语法?或者这是我必须推出自己的自定义授权的情况?
最佳答案
尝试使用位 OR 运算符,如下所示:
[Authorize(Roles= MyEnum.Admin | MyEnum.Moderator)]
public ActionResult myAction()
{
}
如果这不起作用,你可以自己动手。我目前只是在我的项目中做到了这一点。这是我所做的:
public class AuthWhereRole : AuthorizeAttribute
{
/// <summary>
/// Add the allowed roles to this property.
/// </summary>
public UserRole Is;
/// <summary>
/// Checks to see if the user is authenticated and has the
/// correct role to access a particular view.
/// </summary>
/// <param name="httpContext"></param>
/// <returns></returns>
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (httpContext == null)
throw new ArgumentNullException("httpContext");
// Make sure the user is authenticated.
if (!httpContext.User.Identity.IsAuthenticated)
return false;
UserRole role = someUser.Role; // Load the user's role here
// Perform a bitwise operation to see if the user's role
// is in the passed in role values.
if (Is != 0 && ((Is & role) != role))
return false;
return true;
}
}
// Example Use
[AuthWhereRole(Is=MyEnum.Admin|MyEnum.Newbie)]
public ActionResult Test() {}
此外,请确保为您的枚举添加一个标志属性,并确保它们的值都从 1 起。像这样:
[Flags]
public enum Roles
{
Admin = 1,
Moderator = 1 << 1,
Newbie = 1 << 2
etc...
}
左位移位给出值 1、2、4、8、16 等。
好吧,我希望这会有所帮助。
关于asp.net-mvc - asp.net mvc 用多个枚举装饰 [Authorize()],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1148312/