Search code examples
asp.net-coretokenrefresh-tokenhttpclientfactory

Where to store Access and Refresh tokens when consuming external APIs using IHttpClientFactory. Net Core


I am using IHttpClientFactory for sending requests and receiving HTTP responses from my Web API to an external APIs using Net Core 2.2.

The access token and the refresh tokens used to send the request to the API have been stored in the appsettings.json. When a request returns 403 or 401 errors, I get a new token dynamically and add it to the header of the request.

But How Can I update appsettings.json with the new access and refresh token in order to use it for subsequent requests.

Is It there a much better approach to store access and refresh tokens than the appsettings.json?


Solution

  • Since you are using IHttpClinetFactory (and assuming you are using Typed Client as well), you can create your own HttpMessageHandler which would be triggered before any request made by your Typed Client and link it with your typed client via DI like this:

    services.AddHttpClient<IServiceContract, ServiceImplementation>()
                    .AddHttpMessageHandler<TokenHandler>();
    

    Inside that TokenHandler you can check if the request has a token in the headers or not. If not check the cache (Memory Cache) for available tokens, then validate the lifetime of the token.

    If the token is expired or there is no such a token in the cache, issue a new one and store it in the cache.

    I am sure there are better ways, but that what I would do.


    Note: If your application is distributed on multiple servers, then use Distributed Cache instead of the Memory Cache. You can add either easily via DI.


    Update:

    You can register your handler like this:

    services.AddTransient<TokenHandler>();