1

I am trying to accomplish the following

There are multiple roles (role1, role2, role3 etc) and they all have different access levels. Role2 can access the same, as role1, but not role3.

I know I can do it with the authorize attribute in the controller, but is there a different way that may be more elegant instead of just a list of roles in the attribute?

3
  • 1
    Why not combine roles into an aggregate role and use that role on the controller? You can also write your own AutherizationAttribute and define your own custom logic in this class. Commented May 10, 2016 at 9:06
  • @Igor That custom attribute is a great idea! Thanks :) Commented May 10, 2016 at 9:12
  • An other suggestion. If role(N) can access role(N-1) then give users multiple roles. For example user in role3 can also be in role2 and role1. In that way you do not add a list of roles in Authorize attribute, but instead you have 1 role, equal to access level. Commented May 10, 2016 at 9:29

2 Answers 2

2

You can configure authorization policies, means grouping roles into policies.

ASP.NET Core example :

services.AddAuthorization(options => { options.AddPolicy("Role1", policy => policy.RequireRole("Role1"); options.AddPolicy("Role2", policy => policy.RequireRole("Role1", "Role2"); options.AddPolicy("Role3", policy => policy.RequireRole("Role1", "Role2", "Role3"); }); 

And use your policies in your controllers with an authorize attribute :

[Authorize(Policy = "Role3")] 
Sign up to request clarification or add additional context in comments.

Comments

1

I have solved it in the following way:

AuthorizeRoleAttribute.cs

 public class AuthorizeRoleAttribute : AuthorizeAttribute { public AuthorizeRoleAttribute(string role) : base() { var result = Enum.Parse(typeof(RolesEnum), role); int code = result.GetHashCode(); List<string> list = new List<string>(); foreach (var item in Enum.GetValues(typeof(RolesEnum))) { int tmpCode = item.GetHashCode(); if (tmpCode >= code) { list.Add(item.ToString()); } } Roles = string.Join(",", list); } } 

Role ENUM:

 public enum RolesEnum { User = 100, Supervisor = 200, Administration = 300, Admin = 400 } 

Controller:

[AuthorizationRole("Supervisor)] //Some Code

The controller will automaticaly look up what roles have more or equal access to supervisor by the number in the Enum.

1 Comment

If you wanted additional safety turn that string into an enum parameter in the constructor. AuthorizeRoleAttribute(RolesEnum role) : base(). Then you apply it [AuthorizationRole(RolesEnum.Supervisor)]. Now you do not have to worry about spelling mistakes.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.