我正在为我的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”权限,则返回指向“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
}
我已经花了很长时间寻找获取操作属性值的解决方案,但一直没有找到足够好的资源。我是不是缺少正确的关键词? :/
如果有人能提供给我解决方案,那真的会是一大帮助。 非常感谢提前提供解决方案。