Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allow multiple roles to access controller action

Right now I decorate a method like this to allow "members" to access my controller action

[Authorize(Roles="members")] 

How do I allow more than one role? For example the following does not work but it shows what I am trying to do (allow "members" and "admin" access):

[Authorize(Roles="members", "admin")]  
like image 558
codette Avatar asked Mar 31 '09 05:03

codette


People also ask

How does role based authorization work?

Role-based authorization checks specify which roles which the current user must be a member of to access the requested resource. The controller SalaryController is only accessible by users who are members of the HRManager role or the Finance role.

What can be specified on an ASP NET core action to limit access to the action to only authenticated users?

Authorization in ASP.NET Core is controlled with AuthorizeAttribute and its various parameters. In its most basic form, applying the [Authorize] attribute to a controller, action, or Razor Page, limits access to that component to authenticated users.


2 Answers

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

[Authorize(Roles="members,admin")] 
like image 169
Jim Schmehil Avatar answered Sep 26 '22 21:09

Jim Schmehil


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)] 
like image 36
Pablo Claus Avatar answered Sep 25 '22 21:09

Pablo Claus