我目前正在尝试根据用户角色在新的ASP MVC 5应用程序中实现安全性。目的是防止用户在没有特定角色(或更高角色)的情况下访问某些 Controller 或 Controller 方法。根据到目前为止我对这个问题所读的内容,我创建了一个继承AuthorizeAttribute的属性,该属性看起来像这样(MyAppRole是一个枚举,btw):

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

我在方法和/或 Controller 上这样称呼它:
[AuthorizeRoleOrSuperior(MyAppRole.Admin)]
public class MyController : Controller
{
    [AuthorizeRoleOrSuperior(MyAppRole.Admin)]
    public ViewResult Index()
    {
        [...]
    }

    [...]
}

我在构造函数和OnAuthorization方法上设置了一个断点,但是,当我启动该应用程序并调用相关的 Controller 或方法时,即使我什至没有登录,也从未打过任何一个,并且调用了该 Action 。

注意:当我使用AuthorizeAttribute时,它可以正常工作。

知道什么会阻止该属性工作和过滤访问吗?

最佳答案

您是否要从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状态代码。

关于c# - 从AuthorizeAttribute继承的属性不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41121851/

10-13 02:31