1

I am using my own custom Authorize attribute MyAuthorizeAttribute : AuthorizeAttribute to do authorization which is working great. The problem is with role assignment. In the security model i am working with if a user has Admin role User and Manager roles are contained in admin. So

[MyAuthorize(Roles = "Admin")]

is allowed to access all methods. So the intuitive solution is to assign "Admin" on every controller. But is it the cleanest solution?

Also what if i have tens of roles to work with. Code line will look like below:

[MyAuthorize(Roles = "Admin, Role A, Role B... Role Z")]

And what if down the road I decide to rename one of the role name should I use role id's instead?. If i screen for roles in my custom authorize methods then i run the risk of creating a huge switch statement in that function, like below:

switch(Controller Accessed) 
{ 
 case Index: //if user, admin, or any other role exist

 case Manage: //if admin role exists

}
PUG
  • 4,301
  • 13
  • 73
  • 115

1 Answers1

0

Making it easier to rename in the future

If you expect the role names to change, you will get better tool support when you refactor if you use constants or enums.

public static class Roles 
{ 
   public const string UserAdmin = "User Administrator";
   public const string SuperAdmin = "Super Administrator";
   public const string RegularUser = "Regular User";
}

or

public enum Roles 
{ 
   UserAdmin,
   SuperAdmin,
   RegularUser
}

Re-using common groups of permissions

If you find yourself using the same roles in permissions, you can simplify it either by subclassing your MyAuthorize filter or the MVC base controller. Any class that inherits BaseAdminController below would also have the MyAuthorize filter applied.

[MyAuthorize(Roles = Roles.UserAdmin, Roles.SuperAdmin)]
public abstract class BaseAdminController : Controller { 

}

or

public AdminAuthorize : MyAuthorize 
{ 
   public AdminAuthorize() 
   { 
      base.Roles = new[] { Roles.UserAdmin, Roles.SuperAdmin };
   }
}
drch
  • 3,040
  • 1
  • 18
  • 29