【问题标题】:How to allow Caching API endpoint that requires Authorization header?如何允许需要授权标头的缓存 API 端点?
【发布时间】:2019-08-14 09:29:43
【问题描述】:

我正在寻找一种方法来缓存来自在 .NET Core 中开发的 API 端点的响应。对 API 的请求必须具有有效的 Authorization 标头作为要求的一部分。

我看到一些文章提到如果请求包含Authorization 标头,则无法进行缓存,这让我有点惊讶。

那么我应该如何解决这个问题呢?是否有任何库可以为这种场景启用缓存?

【问题讨论】:

  • 这应该不足为奇 :) 不同的用户可能能够获得不同的数据,并且默认缓存这些请求会造成潜在的数据泄漏。可能有控制该行为的设置。
  • 仅供参考:“警告:对包含经过身份验证的客户端信息的内容禁用缓存。仅应为不会根据用户身份或用户是否登录而更改的内容启用缓存。” docs.microsoft.com/en-us/aspnet/core/performance/caching/…
  • @juunas - 谢谢。这说得通。但在我的情况下,棘手的一点是必须需要 Auth 标头,即使响应数据不是用户特定的,例如静态自定义类型和类别枚举等
  • @crgolden - 谢谢。请看我上面的cmets

标签: c# asp.net-core caching .net-core asp.net-core-webapi


【解决方案1】:

对于The Authorization header must not be present.,这是默认设置。

对于ResponseCachingMiddleware,它将调用IResponseCachingPolicyProvider检查是否缓存if (_policyProvider.AllowCacheStorage(context))的响应,如下所示:

// Should we store the response to this request?
if (_policyProvider.AllowCacheStorage(context))
{
    // Hook up to listen to the response stream
    ShimResponseStream(context);

    try
    {
        await _next(httpContext);

        // If there was no response body, check the response headers now. We can cache things like redirects.
        await StartResponseAsync(context);

        // Finalize the cache entry
        await FinalizeCacheBodyAsync(context);
    }
    finally
    {
        UnshimResponseStream(context);
    }

    return;
}

而且,ResponseCachingPolicyProvider 将通过

检查HeaderNames.Authorization
public virtual bool AttemptResponseCaching(ResponseCachingContext context)
{
    var request = context.HttpContext.Request;

    // Verify the method
    if (!HttpMethods.IsGet(request.Method) && !HttpMethods.IsHead(request.Method))
    {
        context.Logger.RequestMethodNotCacheable(request.Method);
        return false;
    }

    // Verify existence of authorization headers
    if (!StringValues.IsNullOrEmpty(request.Headers[HeaderNames.Authorization]))
    {
        context.Logger.RequestWithAuthorizationNotCacheable();
        return false;
    }

    return true;
}

对于ResponseCachingPolicyProvider,它是内部的,您无法从外部Microsoft.AspNetCore.ResponseCaching 更改。不建议为Authorization启用缓存,如果您坚持,可以参考ResponseCaching实现自己的ResponseCachingMiddleware

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-28
    • 2019-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-18
    • 2015-08-17
    相关资源
    最近更新 更多