【发布时间】:2017-04-28 13:24:08
【问题描述】:
我目前正在尝试根据用户角色在新的 ASP MVC 5 应用程序中实现安全性。目标是防止用户在没有特定角色(或更高角色)的情况下访问某些控制器或控制器方法。根据到目前为止我对该问题的阅读,我创建了一个继承 AuthorizeAttribute 的属性,如下所示(MyAppRole 是一个枚举,顺便说一句):
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public sealed class AuthorizeRoleOrSuperiorAttribute : AuthorizeAttribute
{
private MyAppRole _authorizedRole;
public AuthorizeRoleOrSuperiorAttribute(MyAppRole authorizedRole)
{ //Breakpoint here
_authorizedRole = authorizedRole;
}
public override void OnAuthorization(HttpActionContext actionContext)
{ //Breakpoint here
base.OnAuthorization(actionContext);
if (!UserInfo.GetUserRoles().Any(r => (int)r >= (int)_authorizedRole))
throw new UnauthorizedAccessException(ErrorsModule.RoleMissing);
}
}
我在方法和/或控制器上这样称呼它:
[AuthorizeRoleOrSuperior(MyAppRole.Admin)]
public class MyController : Controller
{
[AuthorizeRoleOrSuperior(MyAppRole.Admin)]
public ViewResult Index()
{
[...]
}
[...]
}
我在构造函数和 OnAuthorization 方法上放置了一个断点,但是当我启动应用程序并调用相关的控制器或方法时,我从未点击过它们中的任何一个并且调用了该操作,即使我什至没有登录.
注意:当我使用 AuthorizeAttribute 时,它可以正常工作。
知道什么可以阻止属性工作和过滤访问吗?
【问题讨论】:
标签: c# .net asp.net-mvc-5 authorize-attribute asp.net-roles