ASP.NET MVC 3: Strongly typed Authorize Attribute with multiple users and roles

The ASP.NET MVC 3 framework provides an Authorize attribute that enables you to easily restrict the access to specific controllers and/or actions to predefined roles or users. In detail, the controller or the action is marked with the Authorize attribute that defines which roles or users are granted access to the content which looks as follows:

public class ExampleController : Controller
{
  [Authorize(Users="User1,User2", Roles="Role1,Role2")]
  public ActionResult ExampleAction()
  {
    [...]
  }
}

As you can see in the above example the users and roles are defined using a comma separated string. In complex applications it is often preferable to use a strongly typed approach instead of comma separated strings, which make renaming of roles error-prone and cumbersome. For example, the roles could be defined as constants in a utility class:

public class Roles
{
  public const string Role1 = "Role1";
  public const string Role2 = "Role2";
  public const string Role3 = "Role3";
}

Since one has to use a constant expression when defining attributes one cannot define the Authorize attribute as follows:

[Authorize(Roles = String.Join(",", new[] { Role1, Role2 })))]

To overcome this limitation, I created a custom MultiAuthorize attribute that subclasses the default Authorize attribute and uses arrays to define the Roles and Users properties:

public class MultiAuthorizeAttribute : AuthorizeAttribute
{
  public new string[] Roles
  {
    get { return base.Roles.Split(','); }
    set { base.Roles = string.Join(",", value); }
  }
  public new string[] Users
  {
    get { return base.Users.Split(','); }
    set { base.Users = string.Join(",", value); }
  }
}

Using this custom attribute, one can use arrays containing the strongly-typed roles:

[MultiAuthorize(Roles = new[] { Role1, Role2 })]

Leave a comment

Your email address will not be published. Required fields are marked *

*