【问题标题】:CustomAuthorizeAttribute - HttpActionContext instead of AuthorizationContextCustomAuthorizeAttribute - HttpActionContext 而不是 AuthorizationContext
【发布时间】:2018-05-27 20:14:28
【问题描述】:

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

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

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

【问题讨论】:

    标签: c# asp.net-mvc-4 authorization


    【解决方案1】:

    对我缺少什么/做错了什么有什么想法吗?

    首先,您正在查看一个使用Web API System.Web.Http.AuthorizeAttribute 而不是MVC System.Web.Mvc.AuthorizeAttribute 的示例。 MVC 和 Web API 是独立的框架,两者都不会识别对方的属性。这也是为什么您的 AuthorizeAttribute 中有不同的上下文类型的原因。

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

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

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

    【讨论】:

    • 嗯 - 这绝对解释了它。我想我没有研究不同的授权属性/没有意识到 WebAPI 使用了与 MVC 不同的一个。在这种情况下与 MVC 相比,是否可以使用 System.Web.Http.AuthorizeAttribute?我还将检查“AuthorizeCore”覆盖,因为我绝对希望能够使用匿名属性(无需大杂烩)。我真诚地感谢您的解释!
    • Is it possible to use the System.Web.Http.AuthorizeAttribute in this scenario vs MVC's? 不,但不清楚您为什么要这样做。如果您想在它们之间共享业务逻辑,您可以创建一个实现System.Web.Mvc.IAuthorizationFilterSystem.Web.Http.IAuthorizationFilter 的类,或者您可以创建一个注入两个过滤器的公共服务(有关如何操作的信息,请参阅this answer将 DI 与 AuthorizeAttribute 一起使用。)。
    • 有趣 - 根据我使用提供的链接/说明进行的测试,我认为这对我有用。感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-29
    • 2014-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多