【发布时间】:2019-09-12 19:49:01
【问题描述】:
我想创建[MyAuthorize(Role="R1")] 属性,以便
"R1" 可以进行配置,而不是在 Controller / Action 上进行硬编码。
创建[MyAuthorize(Role="R1")] 的常用方法似乎是
public class MyAuthorizeAttribute : AuthorizeAttribute
{
private readonly string[] _allowedRoles;
public MyAuthorizeAttribute(params string[] roles)
{
this._allowedRoles = roles;
}
protected override bool OnAuthorization(AuthorizationContext
authorizationContext)
{
bool authorize = false;
// Compare current user's Roles with "R1" to figure out if the
// Action / Controller can be executed
return authorize;
}
}
但是如果像"R1" 这样的角色随时可能发生变化怎么办?
即,有一天是"R1",另一天被称为"AssistantManager"。
应用程序必须重新编码以处理此问题。
我想创建一个自定义的[OnAuthorize] 属性,该属性读取
(动作/控制器,角色)作为key value pairs 来自web.config。
例如:--
<add key="Controller1" value="Role1" />
<add key="Action2" value="Role2" />
在属性中..
protected override bool OnAuthorization(AuthorizationContext
authorizationContext)
{
bool authorize = false;
// 1. Read all key values
// 2. determine Action / Controller the user is trying to go
// 3. Compare user's roles with those for Action / Controller
return authorize;
}
我知道 <location .... /> 在 MVC 中的局限性
根据https://stackoverflow.com/a/11765196/807246
我不是在暗示,即使我正在阅读web.config
但是如果我们在应用程序第一次加载时读取(..并存储在会话中??)所有与授权相关的配置呢?
任何更改,例如 "R1" -> "AssistantManager" ;; "R2" -> "Manager" 应该只需要重新启动应用程序,而不必在控制器/操作中进行代码更改。
我想知道这是否是一种有效的方法,或者是否存在安全风险,即使这样,以及任何更好的替代方案。
【问题讨论】:
标签: c# asp.net-mvc authorization authorize-attribute asp.net-authorization