asp.net mvc的装饰[授权()]与多个枚举 [英] asp.net mvc decorate [Authorize()] with multiple enums

查看:100
本文介绍了asp.net mvc的装饰[授权()]与多个枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个控制器,我想两个角色才能够访问它。 1管理员或2主持人

I have a controller and I want two roles to be able to access it. 1-admin OR 2-moderator

我知道你能行[授权(角色=管理员,版主),但我有一个枚举我的角色。随着枚举我只能授权一个角色。我无法弄清楚如何授权两项。

I know you can do [Authorize(Roles="admin, moderators")] but I have my roles in an enum. With the enum I can only authorize ONE role. I can't figure out how to authorize two.

我已经试过像[授权(角色= MyEnum.Admin,MyEnum.Moderator)但不会进行编译。

I have tried something like [Authorize(Roles=MyEnum.Admin, MyEnum.Moderator)] but that wont compile.

曾经有人提出这样的:

 [Authorize(Roles=MyEnum.Admin)]
 [Authorize(MyEnum.Moderator)]
 public ActionResult myAction()
 {
 }

,但它不作为一个或工作。我认为在这种情况下,用户必须两个角色的一部分。我俯瞰一些语法?或者,这是我必须推出自己的自定义授权的情况?

but it doesn't work as an OR. I think in this case the user has to be part of BOTH roles. Am I overlooking some syntax? Or is this a case where I have to roll my own custom authorization?

推荐答案

尝试使用位OR运算符是这样的:

Try using the bit OR operator like this:

[Authorize(Roles= MyEnum.Admin | MyEnum.Moderator)]
public ActionResult myAction()
{
}

如果不工作,你可以只滚你自己。目前,我只是做了这对我的项目。下面是我所做的:

If that doesn't work, you could just roll your own. I currently just did this on my project. Here's what I did:

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往上重视。像这样的:

Also, make sure to add a flags attribute to your enum and make sure they are all valued from 1 and up. Like this:

[Flags]
public enum Roles
{
    Admin = 1,
    Moderator = 1 << 1,
    Newbie = 1 << 2
    etc...
}

左比特移位给出了值1,2,4,8,16等。

The left bit shifting gives the values 1, 2, 4, 8, 16 and so on.

好了,我希望这有助于一点。

Well, I hope this helps a little.

这篇关于asp.net mvc的装饰[授权()]与多个枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆