0

One way of adding an authorization token to your HttpRequestMessage is to simply add it at the configuration level:

services.AddHttpClient<INetworkService, NetworkService>(client =>
{
    client.BaseAddress = new Uri(appConfig.Network.SE);
    client.DefaultRequestHeaders.Add("Authorization", TokenGenerator.GetToken());
})

I don't want to ping the endpoint for a new authorization token every time I make a request so the token is cached. The logic inside TokenGenerator looks in the stored location for a token or creates a new one.

If the token isn't stored, create a new one and return it. If the token is stored, fetch it and return it.

If this kind of authorization was happening at the client level, say in a named or typed client, then I can create a new token as a response to an Unauthorized StatusCode. How can we gracefully handle the scenario when the token is being added in the configuration?


I'm been trying to use Polly with separation of concerns - meaning policies are not shoved into the client class but instead generated and attached at configuration level. I've been unable to find a way to mutate the request header in order to add the new token.

return Policy
    .HandleResult<HttpResponseMessage>(response => response.StatusCode == HttpStatusCode.Unauthorized)
    .RetryAsync(
        retryCount : 1, 
        onRetryAsync: async (responseDelegate, retryNumber, context) =>
        {      
            // Case 1: Token Expired
            ?? how to mutate request message with new auth header???
            // Case 2: Actually unathorized
        }
8protons
  • 3,591
  • 5
  • 32
  • 67
  • Does this answer your question? [Refresh Token using Polly with Typed Client](https://stackoverflow.com/questions/56976156/refresh-token-using-polly-with-typed-client) – Peter Csala Nov 20 '20 at 07:52
  • @PeterCsala no, I’m not shoving policy logic into the client. – 8protons Nov 20 '20 at 08:06
  • 1
    You have two options (that I'm aware of) either you replace the client with an instance where the new token is being set, like [this](https://nodogmablog.bryanhogan.net/2017/05/re-authorization-and-onretry-with-polly/) or you retrieve the access token from the context and refresh that data inside the context on retry like [this](https://www.jerriepelser.com/blog/refresh-google-access-token-with-polly/). – Peter Csala Nov 20 '20 at 08:13

0 Answers0