Yve*_*omb 2 asp.net-mvc inheritance authorization asp.net-mvc-controller asp.net-roles
我已经创建了控制器类来协助角色授权.
我有一个基类ControllersAuthorities,这是最高级别的权威.我已经创建了其他类来扩展每个基类.
[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 { }
Run Code Online (Sandbox Code Playgroud)
第一个问题,请问Owner,Admin和Employee角色可以访问SalesController?
在我的项目控制器中实现这些类时.如果我离开[Authorize]uncommented,这会覆盖继承的权限角色吗?
//[Authorize]
public class AccountController:ControllerAuthorities
{
Run Code Online (Sandbox Code Playgroud)
Mst*_*san 13
查看AttributeUsage属性的Authorize 属性 ;
[AttributeUsageAttribute(AttributeTargets.Class | AttributeTargets.Method,
Inherited = true, AllowMultiple = true)]
public class AuthorizeAttribute : FilterAttribute, IAuthorizationFilter
Run Code Online (Sandbox Code Playgroud)
Inherited= true 表示使用此属性修饰的类的子类可以继承此属性.
AllowMultiple=true 表示此属性可以在同一实体上放置多次.
使用继承的属性并允许使用相同的属性,您SalesController 可以将其视为
[Authorize(Roles = "Sales")]
[Authorize(Roles = "Employee")]
[Authorize(Roles = "Admin")]
[Authorize(Roles = "Owner")]
public abstract class SalesController:EmployeeController { }
Run Code Online (Sandbox Code Playgroud)
您可以使用此代码在运行时测试它.
var a = typeof(SalesController).GetCustomAttributes(true).ToArray();
Run Code Online (Sandbox Code Playgroud)
第一个问题,请问Owner,Admin和Employee角色可以访问SalesController?继承的属性分开,以便它们应用independently.For一个用户访问SalesController,用户必须拥有所有角色(owner,admin,employee和sales)不是其中之一.
看看之间的区别
[Authorize(Roles = "Sales")]
[Authorize(Roles = "Employee")]
[Authorize(Roles = "Admin")]
[Authorize(Roles = "Owner")]
public abstract class SalesController:EmployeeController { }
Run Code Online (Sandbox Code Playgroud)
和
[Authorize(Roles = "Owner,Admin,Employee,Sales")]
public abstract class SalesController:EmployeeController { }
Run Code Online (Sandbox Code Playgroud)
第二个问题:如果你留下未[Authorize]注释的相同逻辑AccountController就好
[Authorize(Roles = "Owner")]
[Authorize]
public class AccountController:ControllerAuthorities{}
Run Code Online (Sandbox Code Playgroud)
因此,它不会覆盖继承的权限,只会创建authorize属性的多次使用,因为Authorize属性允许多次使用.如果AllowMultiple是false在Authorize属性definiton然后派生类可以重写基类的属性.
| 归档时间: |
|
| 查看次数: |
3090 次 |
| 最近记录: |