【问题标题】:Attribute inheriting from AuthorizeAttribute not working从 AuthorizeAttribute 继承的属性不起作用
【发布时间】: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


    【解决方案1】:

    您是否从 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);
        }
    }
    

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

    注意参数区别: OnAuthorization(AuthorizationContext filterContext)public override void OnAuthorization(HttpActionContext actionContext)

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

    【讨论】:

    • 谢谢,这正是我想要的,现在一切都按预期工作。从现在开始,我会记得注意我继承的类的命名空间...
    猜你喜欢
    • 1970-01-01
    • 2010-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-03
    • 1970-01-01
    • 1970-01-01
    • 2013-01-14
    相关资源
    最近更新 更多