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
}