ASP.NET MVC Authorize user with many roles

2019-03-24 07:48发布

问题:

I need to authorize a Controller in my ASP.NET MVC application to users which have two roles. I am using Authorize attribute like this:

[Authorize(Roles = "Producer, Editor")]

But this allows Producers and Editors to the controller. I want only to allow users having both roles, not just one of them.

How could i achive this?

回答1:

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.



回答2:

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{
}