【发布时间】:2012-11-02 18:45:57
【问题描述】:
我正在为我的应用程序在 ASP.NET MVC 中使用基于权限的授权系统。 为此,我创建了一个自定义授权属性
public class MyAuthorizationAttribute : AuthorizeAttribute
{
string Roles {get; set;}
string Permission {get; set;}
}
这样我就可以通过角色或带有注释的特定权限密钥来授权用户,例如
public class UserController : Controller
{
[MyAuthorization(Roles="ADMIN", Permissions="USER_ADD")]
public ActionResult Add()
[MyAuthorization(Roles="ADMIN", Permissions="USER_EDIT")]
public ActionResult Edit()
[MyAuthorization(Roles="ADMIN", Permissions="USER_DELETE")]
public ActionResult Delete()
}
然后我用类似的逻辑(伪代码)覆盖 MyAuthorizationAttribute 类中的 AuthorizeCore() 方法
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if(user not authenticated)
return false;
if(user has any role of Roles)
return true;
if(user has any permission of Permissions)
return true;
return false;
}
到目前为止一切正常。
现在我需要某种扩展方法,以便我可以在视图页面中动态生成操作 url,该操作 url 将基于给定操作的 MyAuthorization 属性授权逻辑返回操作 url。喜欢
@Url.MyAuthorizedAction("Add", "User")
如果用户具有管理员角色或具有“USER_ADD”权限(在操作的属性中定义),则将 url 返回到“用户/添加”,否则返回空字符串。
但在互联网上搜索了几天后,我无法弄清楚。 :(
到目前为止,我只发现了这个"Security aware" action link?,它通过执行该操作的所有操作过滤器直到失败为止。
这很好,但我认为每次调用 MyAuthorizedAction() 方法时执行所有操作过滤器都会产生开销。此外它也不适用于我的版本(MVC 4 和 .NET 4.5)
我所需要的只是检查经过身份验证的用户的角色、权限(将存储在会话中)与授权角色和给定操作的权限。如下所示(伪代码)
MyAuthorizedAction(string actionName, string controllerName)
{
ActionObject action = SomeUnknownClass.getAction(actionName, controllerName)
MyAuthorizationAttribute attr = action.returnsAnnationAttributes()
if(user roles contains any in attr.Roles
or
user permissions contains any attr.Permissions)
{
return url to action
}
return empty string
}
我一直在寻找获取动作属性值的解决方案,根本找不到足够好的资源。我错过了正确的关键字吗? :/
如果有人可以为我提供真正有很大帮助的解决方案。 提前感谢您的解决方案
【问题讨论】:
-
您想根据用户的权限创建链接,而不是在用户点击 url 时验证用户权限?
-
没关系,我错过了 AuthorizeCore 第一次通读...
标签: c# asp.net-mvc razor