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 of Authorize
attribute ;
[AttributeUsageAttribute(AttributeTargets.Class | AttributeTargets.Method,
Inherited = true, AllowMultiple = true)]
public class AuthorizeAttribute : FilterAttribute, IAuthorizationFilter
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 as
[Authorize(Roles = "Sales")]
[Authorize(Roles = "Employee")]
[Authorize(Roles = "Admin")]
[Authorize(Roles = "Owner")]
public abstract class SalesController:EmployeeController { }
And you can test this at runtime with this code.
var a = typeof(SalesController).GetCustomAttributes(true).ToArray();
First question, will the Owner
, Admin
and Employee
Roles have access to the SalesController
?
Inherited attributes are separated so they are applied independently.For one user to access SalesController
, user must have all roles(owner
,admin
,employee
and sales
) not one of them.
See the difference between
[Authorize(Roles = "Sales")]
[Authorize(Roles = "Employee")]
[Authorize(Roles = "Admin")]
[Authorize(Roles = "Owner")]
public abstract class SalesController:EmployeeController { }
and
[Authorize(Roles = "Owner,Admin,Employee,Sales")]
public abstract class SalesController:EmployeeController { }
Second question: If you leave [Authorize]
uncommented with same logic AccountController
is like
[Authorize(Roles = "Owner")]
[Authorize]
public class AccountController:ControllerAuthorities{}
So it does not override inherited authority just creates multiple usage of authorize attribute because multiple usage is allowed for Authorize
attribute. If AllowMultiple
were false
in Authorize
attribute definiton then derived class could override the attribute in base class.