Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Authorize Attribute with Multiple Roles

I would like to add Authorization to a controller, for multiple Roles at once.

Normally that would look like this:

[Authorize(Roles = "RoleA,RoleB,RoleC")] public async Task<ActionResult> Index() { } 

But I have stored my Roles in consts, since they might change or be extended at some point.

public const RoleA = "RoleA"; public const RoleB = "RoleB"; public const RoleC = "RoleC"; 

I cannot do this, since the string must be known at compile time:

[Authorize(Roles = string.join(",",RoleA,RoleB,RoleC)] public async Task<ActionResult> Index() { } 

Is there a way to circumvent the problem?

I COULD write a const which simply contains "RoleA,RoleB,RoleC" - but I dislike magic strings and this is a magic string. Changing the name of a Role and forgetting to change the combined string would be a disaster.

I am using MVC5. ASP.NET Identity and the Role are known at compile time.

like image 228
Christian Sauer Avatar asked Jun 12 '14 10:06

Christian Sauer


People also ask

How do I Authorize a role in MVC?

Open Visual Studio 2015 or an editor of your choice and create a new project. Choose "web application" project and give an appropriate name to your project. Select "empty" template, check on the MVC box, and click OK. Right-click on the Models folder and add a database model.

How does the Authorize attribute work?

If a user is not authenticated, or doesn't have the required user name and role, then the Authorize attribute prevents access to the method and redirects the user to the login URL. When both Roles and Users are set, the effect is combined and only users with that name and in that role are authorized.

Where can the Authorize attribute can be applied?

You can place the Authorize attribute on a controller or on individual actions inside the controller. When we place the Authorize attribute on the controller itself, the authorize attribute applies to all of the actions inside.


1 Answers

Try to create custom authorize attribute like this.

public class AuthorizeRolesAttribute : AuthorizeAttribute {     public AuthorizeRolesAttribute(params string[] roles) : base()     {         Roles = string.Join(",", roles);     } } 

Assuming your roles will be the same for multiple controllers, create a helper class:

public static class Role {     public const string Administrator = "Administrator";     public const string Assistant = "Assistant"; } 

Then use it like so:

public class MyController : Controller {     [AuthorizeRoles(Role.Administrator, Role.Assistant)]     public ActionResult AdminOrAssistant()     {                                return View();     } } 
like image 200
MacGyver Avatar answered Oct 04 '22 04:10

MacGyver