How to allow Caching API endpoint that requires Authorization header?

狂风中的少年 提交于 2021-02-09 10:51:39

问题


I was looking at a way for caching responses from an API endpoint developed in .NET Core. The request to the API must have a valid Authorization header as part the requirement.

I came across a few articles mentioning that caching wouldn't be possible if the request contains Authorization header, which was a bit of surprise to me.

So how should I tackle this problem? Are there any libraries that can possibly enable caching for this kind of scenario?


回答1:


For The Authorization header must not be present., this is by default.

For ResponseCachingMiddleware which will call IResponseCachingPolicyProvider to check whether to cache the reponse by if (_policyProvider.AllowCacheStorage(context)) like below:

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

And, ResponseCachingPolicyProvider will check HeaderNames.Authorization by

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

For ResponseCachingPolicyProvider, it is internal which you could not change from outside Microsoft.AspNetCore.ResponseCaching. It is not recommended to enable cache for Authorization, if you insist on, you could implement your own ResponseCachingMiddleware by refer ResponseCaching.



来源:https://stackoverflow.com/questions/57491941/how-to-allow-caching-api-endpoint-that-requires-authorization-header

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!