I've created controller classes to assist with Role authorization.
I have a base class ControllersAuthorities
, which is the highest level of authority. I have created the other classes to extend each base class.
[Authorize(Roles = "Owner")]
public abstract class ControllerAuthorities:Controller { }
[Authorize(Roles = "Admin")]
public abstract class AdminController:ControllerAuthorities { }
[Authorize(Roles = "Employee")]
public abstract class EmployeeController:AdminController { }
[Authorize(Roles = "Sales")]
public abstract class SalesController:EmployeeController { }
First question, will the Owner
, Admin
and Employee
Roles have access to the SalesController
?
When implementing these classes in my project controllers.
If I leave the [Authorize]
uncommented, will this override the inherited authority Role?
//[Authorize]
public class AccountController:ControllerAuthorities
{
Looking at
AttributeUsage
attribute ofAuthorize
attribute ;Inherited= true
means that subclasses of the class which decorated with this attribute can inherit this attribute.AllowMultiple=true
means that this attribute can be placed more than once on same entity.With inherited attributes and allowed usage of same attribute your
SalesController
can be considered asAnd you can test this at runtime with this code.
First question, will the
Owner
,Admin
andEmployee
Roles have access to theSalesController
? Inherited attributes are separated so they are applied independently.For one user to accessSalesController
, user must have all roles(owner
,admin
,employee
andsales
) not one of them.See the difference between
and
Second question: If you leave
[Authorize]
uncommented with same logicAccountController
is likeSo it does not override inherited authority just creates multiple usage of authorize attribute because multiple usage is allowed for
Authorize
attribute. IfAllowMultiple
werefalse
inAuthorize
attribute definiton then derived class could override the attribute in base class.No, They can't access to
SalesController
. Inheritance makes your code like this:And since
SalesController
requires additional role, named Sales won't be accessible. Key to AccessSalesController
: The user should be in All the mentioned roles.Yes, since
AccountController
derived fromControllerAuthorities
which requiresOwner
role.Note that the controllers in MVC are just classes with some additional features to handle requests. There's no difference with
class
concepts.Tip : Look at the followings:
[Authorize(Roles = "Sales, Employee, Admin, Owner")]
allows the user which have one of the roles. In another words, This acts like OR (||
) operation.[Authorize(Roles = "Sales", "Employee", "Admin", "Owner")]
allows the user which have All of the roles. In another words, This acts like And (&
) operation.The last one is like your question. That's equal to the following too:
For more clarification than this! see How to authorize a set of controllers without placing the annotation on each one?