1
votes

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?

2
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. - Igor
@Igor That custom attribute is a great idea! Thanks :) - Faling Dutchman
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. - tmg

2 Answers

2
votes

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")]
1
votes

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.