ASP.NET MVC Authorize user with many roles

萝らか妹 提交于 2019-12-03 05:11:26

As the question states, when multiple roles are given in a single Authorize() call they are applied such that if the user belongs to any of the roles listed they will be granted access; like a logical OR operator.

Alternatively, to achieve the effect of a logical AND operator you can apply the Authorize attribute multiple times. Eg..

[Authorize(Roles = "Producer")]
[Authorize(Roles = "Editor")]
public ActionResult Details(int id) {
    // Only available to users who are Producers AND Editors
}

For the example above, the action body is accessible only to users who belong to the Producer and the Editor roles.

Rudi points out in the comments this lets you create some reasonably complex access rules without needing to implement a custom AuthorizeAttribute. For example, in the code below users can execute the action if they are both: a) in the Enabled role and b) in either the Editor or Admin roles.

[Authorize(Roles = "Enabled")]
[Authorize(Roles = "Editor,Admin")]
public ActionResult Details(int id) {
    // Only available to users who are Enabled AND either an Admin OR an Editor
}

I'm not sure which version brought this in but it works in at least MVC 4 and 5.

You should do your custom AuthorizeAttribute

public class AuthorizeMultipleAttribute : AuthorizeAttribute
{

   //Authorize multiple roles
   public string MultipleRoles { get; set; }

  protected override bool AuthorizeCore(HttpContextBase httpContext)
  {
      var isAuthorized = base.AuthorizeCore(httpContext);
      if (!isAuthorized)
      {                
        return false;
      }

      //Logic here
      //Note: Make a split on MultipleRoles, by ','
      //User is in both roles => return true, else return false
  }

}

DEMO :

[AuthorizeMultiple(MultipleRoles ="Role1,Role2")]
public class UserController{
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!