继承自AuthorizeAttribute的属性不起作用

Zip*_*ive 4 .net c# authorize-attribute asp.net-roles asp.net-mvc-5

我目前正在尝试基于用户角色在新的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);
    }
}
Run Code Online (Sandbox Code Playgroud)

我在方法和/或控制器上这样称呼它:

[AuthorizeRoleOrSuperior(MyAppRole.Admin)]
public class MyController : Controller
{
    [AuthorizeRoleOrSuperior(MyAppRole.Admin)]
    public ViewResult Index()
    {
        [...]
    }

    [...]
}
Run Code Online (Sandbox Code Playgroud)

我在构造函数和OnAuthorization方法上放置了一个断点,但是,当我启动应用程序并调用相关的控制器或方法时,我从未点击任何一个并且操作被调用,即使我甚至没有登录.

注意:AuthorizeAttribute在我使用时正常工作.

知道什么可以阻止属性工作和过滤访问?

小智 8

您是否从System.Web.Http.AuthorizeAttribute继承该属性?它的工作方式与System.Web.Mvc.AuthorizeAttribute不同.

尝试继承System.Web.Mvc.AuthorizeAttribute.

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public sealed class AuthorizeRoleOrSuperiorAttribute : System.Web.Mvc.AuthorizeAttribute
{
    private MyAppRole _authorizedRole;

    public AuthorizeRoleOrSuperiorAttribute(MyAppRole authorizedRole)
    { //Breakpoint here
        _authorizedRole = authorizedRole;
    }

    public override void OnAuthorization(AuthorizationContext filterContext)
    { //Breakpoint here
        base.OnAuthorization(filterContext);

        if (!UserInfo.GetUserRoles().Any(r => (int)r >= (int)_authorizedRole))
            throw new UnauthorizedAccessException(ErrorsModule.RoleMissing);
    }
}
Run Code Online (Sandbox Code Playgroud)

这至少应该让你达到断点.

注意参数差异: OnAuthorization(AuthorizationContext filterContext)public override void OnAuthorization(HttpActionContext actionContext)

您还可以设置filterContext.Result = new HttpUnauthorizedResult();获取正确的401 http状态代码.