Search code examples
c#asp.net-corecaching.net-coreasp.net-core-webapi

How to allow Caching API endpoint that requires Authorization header?


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.

Response caching conditions

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


Solution

  • 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.