asp.net-mvc 允许多个角色访问控制器操作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/700166/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-07 23:27:19  来源:igfitidea点击:

Allow multiple roles to access controller action

asp.net-mvccontrollerroles

提问by codette

Right now I decorate a method like this to allow "members" to access my controller action

现在我装饰了一个这样的方法来允许“成员”访问我的控制器操作

[Authorize(Roles="members")]

How do I allow more than one role?For example the following does not work but it shows what I am trying to do (allow "members" and "admin" access):

我如何允许多个角色?例如,以下不起作用,但它显示了我正在尝试做的事情(允许“成员”和“管理员”访问):

[Authorize(Roles="members", "admin")] 

回答by Jim Schmehil

Another option is to use a single authorize filter as you posted but remove the inner quotations.

另一种选择是在您发布时使用单个授权过滤器,但删除内部引用。

[Authorize(Roles="members,admin")]

回答by Pablo Claus

If you want use custom roles, you can do this:

如果你想使用自定义角色,你可以这样做:

CustomRolesclass:

CustomRoles班级:

public static class CustomRoles
{
    public const string Administrator = "Administrador";
    public const string User = "Usuario";
}

Usage

用法

[Authorize(Roles = CustomRoles.Administrator +","+ CustomRoles.User)]

If you have few roles, maybe you can combine them (for clarity) like this:

如果你的角色很少,也许你可以像这样组合它们(为了清楚起见):

public static class CustomRoles
{
     public const string Administrator = "Administrador";
     public const string User = "Usuario";
     public const string AdministratorOrUser = Administrator + "," + User;  
}

Usage

用法

[Authorize(Roles = CustomRoles.AdministratorOrUser)]

回答by Mihkel Müür

One possible simplification would be to subclass AuthorizeAttribute:

一种可能的简化是子类化AuthorizeAttribute

public class RolesAttribute : AuthorizeAttribute
{
    public RolesAttribute(params string[] roles)
    {
        Roles = String.Join(",", roles);
    }
}

Usage:

用法:

[Roles("members", "admin")]

Semantically it is the same as Jim Schmehil's answer.

从语义上讲,它与 Jim Schmehil 的回答相同。

回答by Bernardo Loureiro

For MVC4, using a Enum(UserRoles) with my roles, I use a custom AuthorizeAttribute.

对于 MVC4,在我的角色中使用Enum( UserRoles),我使用自定义AuthorizeAttribute.

On my controlled action, I do:

在我的受控动作中,我会:

[CustomAuthorize(UserRoles.Admin, UserRoles.User)]
public ActionResult ChangePassword()
{
    return View();
}

And I use a custom AuthorizeAttributelike that:

我使用这样的习惯AuthorizeAttribute

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
public class CustomAuthorize : AuthorizeAttribute
{
    private string[] UserProfilesRequired { get; set; }

    public CustomAuthorize(params object[] userProfilesRequired)
    {
        if (userProfilesRequired.Any(p => p.GetType().BaseType != typeof(Enum)))
            throw new ArgumentException("userProfilesRequired");

        this.UserProfilesRequired = userProfilesRequired.Select(p => Enum.GetName(p.GetType(), p)).ToArray();
    }

    public override void OnAuthorization(AuthorizationContext context)
    {
        bool authorized = false;

        foreach (var role in this.UserProfilesRequired)
            if (HttpContext.Current.User.IsInRole(role))
            {
                authorized = true;
                break;
            }

        if (!authorized)
        {
            var url = new UrlHelper(context.RequestContext);
            var logonUrl = url.Action("Http", "Error", new { Id = 401, Area = "" });
            context.Result = new RedirectResult(logonUrl);

            return;
        }
    }
}

This is part of modifed FNHMVC by Fabricio Martínez Tamayo https://github.com/fabriciomrtnz/FNHMVC/

这是 Fabricio Martínez Tamayo https://github.com/fabriciomrtnz/FNHMVC/修改的 FNHMVC 的一部分

回答by Renê R. Silva

Another clear solution, you can use constants to keep convention and add multiple [Authorize] attributes. Check this out:

另一个明确的解决方案,您可以使用常量来保持约定并添加多个 [Authorize] 属性。看一下这个:

public static class RolesConvention
{
    public const string Administrator = "Administrator";
    public const string Guest = "Guest";
}

Then in the controller:

然后在控制器中:

[Authorize(Roles = RolesConvention.Administrator )]
[Authorize(Roles = RolesConvention.Guest)]
[Produces("application/json")]
[Route("api/[controller]")]
public class MyController : Controller

回答by GER

If you find yourself applying those 2 roles often you can wrap them in their own Authorize. This is really an extension of the accepted answer.

如果您发现自己经常应用这 2 个角色,则可以将它们包装在自己的 Authorize 中。这实际上是已接受答案的扩展。

using System.Web.Mvc;

public class AuthorizeAdminOrMember : AuthorizeAttribute
{
    public AuthorizeAdminOrMember()
    {
        Roles = "members, admin";
    }
}

And then apply your new authorize to the Action. I think this looks cleaner and reads easily.

然后将您的新授权应用于 Action。我认为这看起来更干净并且易于阅读。

public class MyController : Controller
{
    [AuthorizeAdminOrMember]
    public ActionResult MyAction()
    {
        return null;
    }
}

回答by Daniel DirtyNative Martin

Using AspNetCore 2.x, you have to go a little different way:

使用 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()));
    }
}

just use it like this:

就像这样使用它:

[Authorize(YourEnum.Role1, YourEnum.Role2)]

回答by kinzzy goel

Better code with adding a subclass AuthorizeRole.cs

通过添加子类获得更好的代码 AuthorizeRole.cs

    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
    class AuthorizeRoleAttribute : AuthorizeAttribute
    {
        public AuthorizeRoleAttribute(params Rolenames[] roles)
        {
            this.Roles = string.Join(",", roles.Select(r => Enum.GetName(r.GetType(), r)));
        }
        protected override void HandleUnauthorizedRequest(System.Web.Mvc.AuthorizationContext filterContext)
        {
            if (filterContext.HttpContext.Request.IsAuthenticated)
            {
                filterContext.Result = new RedirectToRouteResult(
                new RouteValueDictionary {
                  { "action", "Unauthorized" },
                  { "controller", "Home" },
                  { "area", "" }
                  }
              );
                //base.HandleUnauthorizedRequest(filterContext);
            }
            else
            {
                filterContext.Result = new RedirectToRouteResult(
                new RouteValueDictionary {
                  { "action", "Login" },
                  { "controller", "Account" },
                  { "area", "" },
                  { "returnUrl", HttpContext.Current.Request.Url }
                  }
              );
            }
        }
    }

How to use this

如何使用这个

[AuthorizeRole(Rolenames.Admin,Rolenames.Member)]

public ActionResult Index()
{
return View();
}

回答by Orsit Moel

Intent promptInstall = new Intent(android.content.Intent.ACTION_VIEW);
promptInstall.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
promptInstall.setDataAndType(Uri.parse("http://10.0.2.2:8081/MyAPPStore/apk/Teflouki.apk"), "application/vnd.android.package-archive" );

startActivity(promptInstall);