asp.net-mvc - asp.net mvc 用多个枚举装饰 [Authorize()]

标签 asp.net-mvc authorization roles

我有一个 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/

相关文章:

asp.net-mvc - Azure 身份验证 .net MVC 超时设置

node.js - 将 NodeJS Rest 服务与 wso2 集成

json - 根据用户角色返回 JSON

azure - 如何在Azure下的Windows Server 2012 R2下向IIS添加跟踪

jquery - 在 JQuery 中获取本地化语言

asp.net-mvc - 与使用 HTML + Javascript + Services 应用程序相比,使用传统 MVC 框架有哪些优势?

asp.net-mvc - 为什么部署到 Azure 网站时,AllowAnonymous 不起作用?

reactjs - React Native Firebase 验证码

java - Java EE 中基于角色的菜单

c# - 用于匹配不以 .ext(扩展名)结尾的字符串(1 个以上字符)的正则表达式