0

I'm using Polly and IHttpClientFactory to handle my fault tolerance, which is working fine for retry and circuit breaker in .NET Core 3.1

I'm not trying to handle any 401's, which I can do within the controller, but I can't find a way to refresh the token from the StartUp

This is my policy in startup

IAsyncPolicy<HttpResponseMessage> httpWaitAndRetryPolicy =
    Policy.HandleResult<HttpResponseMessage>(r => !r.IsSuccessStatusCode)
        .WaitAndRetryAsync(3, sleepDurationProvider: retryAttempt => TimeSpan.FromSeconds(retryAttempt),
            onRetry: (httpResponseMessage, span, retryCount, ctx) =>
            {
                if (httpResponseMessage.Result.StatusCode == System.Net.HttpStatusCode.Unauthorized)
                {
                    PerformReauthorazation();
                }
                Console.WriteLine($"Retrying({retryCount})...");
            });

private void PerformReauthorazation()
{
    var x = 0;
    //do something
}

But this is detached from from the actual controller as you would expect.

To reauthorise I need to call and get a new token to an end-point with all the credentials.

Then I add the following header

_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearerToken.AccessToken);

But how do I do this from the StartUp?

Peter Csala
  • 17,736
  • 16
  • 35
  • 75
Coppermill
  • 6,676
  • 14
  • 67
  • 92
  • Have you read [this](https://nodogmablog.bryanhogan.net/2017/05/re-authorization-and-onretry-with-polly/) or [this](https://www.jerriepelser.com/blog/refresh-google-access-token-with-polly/) – Peter Csala Nov 20 '20 at 07:50
  • 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:50

0 Answers0