309

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

[Authorize(Roles="members")]

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

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

11 回答 11

645

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

[Authorize(Roles="members,admin")]
于 2009-10-01T13:14:00.350 回答
152

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

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)]
于 2012-05-23T15:32:34.653 回答
98

一种可能的简化是子类AuthorizeAttribute

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

用法:

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

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

于 2014-03-25T18:21:25.217 回答
19

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

在我控制的行动中,我会:

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

我使用这样的自定义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;
        }
    }
}

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

于 2014-02-19T20:42:59.333 回答
4

使用 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)]
于 2018-10-18T18:39:41.643 回答
3

您可以在 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 个角色。

于 2021-01-06T02:33:33.117 回答
3

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

using System.Web.Mvc;

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

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

public class MyController : Controller
{
    [AuthorizeAdminOrMember]
    public ActionResult MyAction()
    {
        return null;
    }
}
于 2018-02-15T19:57:48.420 回答
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
于 2017-02-22T00:19:44.687 回答
3

添加子类的代码更好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 }
                  }
              );
            }
        }
    }

如何使用这个

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

public ActionResult Index()
{
return View();
}
于 2016-01-27T07:20:44.083 回答
0
[Authorize(Roles="admin")]
[Authorize(Roles="members")]

将在AND需要时工作(如问题所问),而答案显示OR版本。在https://docs.microsoft.com/en-us/aspnet/core/security/authorization/roles?view=aspnetcore-6.0#adding-role-checks查看更多信息

于 2022-03-01T01:17:38.653 回答
-9
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);
于 2020-01-03T15:04:37.070 回答