asp.net mvc - Allow multiple roles to access controller action

ID : 10256

viewed : 32

Tags : asp.net-mvccontrollerrolesasp.net-mvc

Top 5 Answer for asp.net mvc - Allow multiple roles to access controller action

vote vote

97

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

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

87

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

CustomRoles class:

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)] 
vote vote

76

One possible simplification would be to subclass 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.

vote vote

69

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

On my controlled action, I do:

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

And I use a custom AuthorizeAttribute like that:

[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/

vote vote

55

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

[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)] 

Top 3 video Explaining asp.net mvc - Allow multiple roles to access controller action

Related QUESTION?