Attribute inheriting from AuthorizeAttribute not working

三世轮回 提交于 2019-12-04 10:35:03

Are you inheriting the attribute from System.Web.Http.AuthorizeAttribute? It works differently than System.Web.Mvc.AuthorizeAttribute.

Try inheriting from System.Web.Mvc.AuthorizeAttribute instead.

[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);
    }
}

That should at least make you hit the breakpoint.

Note parameter difference in: OnAuthorization(AuthorizationContext filterContext) and public override void OnAuthorization(HttpActionContext actionContext)

You can also set filterContext.Result = new HttpUnauthorizedResult(); to get the correct 401 http status code.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!