CustomAuthorizeAttribute - HttpActionContext 而不是 AuthorizationContext

CustomAuthorizeAttribute - HttpActionContext instead of AuthorizationContext

我正在尝试在 MVC4/Razor 中创建自定义授权属性,但在自定义授权属性下的 "AllowAnnoymous" 属性 运行 有问题(它似乎忽略了它).这一切都很好,花花公子,因为我找到了一个解决方案(见下文),方法是检查控制器或操作是否包含允许匿名属性,如果是,则允许通过。

但是,我看到当我创建 "AuthorizeAttribute" class 并尝试实现 "OnAuthorization" 覆盖时,它将对象处理程序设置为 "AuthorizationContext" 但在下面的示例和我在这里找到的许多其他示例中,似乎不应该使用 "AuthorizationContext" - 而应该是 "HttpActionContext"。虽然我试图用 "HttpActionContext" 替换它,但覆盖然后失败说没有合适的方法。我有什么想法 missing/doing 错了吗?

Example Found Here (By Jammer)

private static bool SkipAuthorization(HttpActionContext actionContext)
{
    Contract.Assert(actionContext != null);

    return actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any()
               || actionContext.ControllerContext.ControllerDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any();
}

public override void OnAuthorization(HttpActionContext actionContext)
{
        base.OnAuthorization(actionContext);
}

我的代码

private override void OnAuthorization(AuthorizationContext filterContext) // Not sure how to change this to HttpActionContext
{
    if (filterContext == null) throw new ArugmentException("filterContext");
    if (!AllowAnnonymous(new HttpActionContext()))
    {
        throw new HttpResponseException(HttpStatusCode.UnAuthorized);
    }
    else
    {
        base.OnAuthorization(filterContext);
    }
}

Any ideas on what I'm missing/doing wrong?

首先,您正在查看使用 Web API System.Web.Http.AuthorizeAttribute instead of the MVC System.Web.Mvc.AuthorizeAttribute 的示例。 MVC 和 Web API 是独立的框架,两者都不会识别对方的属性。这也是您在 AuthorizeAttribute.

中使用不同上下文类型的原因

其次,您的自定义 AuthorizeAttribute 无法识别 AllowAnonymousAttribute 的原因是因为您重写了检查 OnAuthorization 的逻辑(以及处理其他重要逻辑带输出缓存)。如果您改为覆盖 AuthorizeCore 和 return true/false,那么您将不会跳过这个重要的逻辑。

如果您需要更改用户重定向的位置,您可以覆盖 HandleUnauthorizedRequest,它仅在授权失败时执行。

最后,如果您需要访问 ActionDescriptor 来扫描您自己的属性,它会通过 AuthorizationContext.ActionDescriptor 传递到 OnAuthorization。不幸的是,它不会自动传递到 AuthorizeCore,但是您可以通过在 OnAuthorization 中将其设置为 HttpContext.Items 来解决这个问题,就像在 .

中一样