2

I am trying to use Polly retry policy for handling unauthorised responses which require a token refresh.

But I seem to be stuck in a loop. So the unauthorised error is captured and processed by Polly, I call a method to refresh the token which works and I get a new token set in my app, but for some reason the authorisation failure occurs again!

It seems as if when the retry is executed it is using the original Token and not the new one, and this is causing the issue. But I don't know how to overcome this problem.

Creation of my Refit Rest client

private static void AddRestClient(IServiceCollection services, string hMClientBaseUrl, AuthService authService)
{
    var unauthPolicy = Policies.GetUnauthPolicy(authService);

    services.AddRefitClient<IHomeMonitorRestClient>(new RefitSettings
    {
        ContentSerializer = new NewtonsoftJsonContentSerializer(DefaultJsonSettings.Settings),
    })
        .ConfigureHttpClient(c => c.BaseAddress = new Uri(hMClientBaseUrl))
        .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
        {
            ServerCertificateCustomValidationCallback = (message, cert, chain, sslErrors) => true
        })

    .AddPolicyHandler(unauthPolicy);
}

public static AsyncRetryPolicy<HttpResponseMessage> GetUnauthPolicy(AuthService authService)
{
    return Policy.HandleResult<HttpResponseMessage>(
      r => r.StatusCode == HttpStatusCode.Unauthorized)
     .WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(1), onRetryAsync: async (response, timespan, retryNo, context) =>
          {
              if (response.Result.StatusCode == HttpStatusCode.Unauthorized)
              {
                  await authService.RefreshToken(); 
              }
          });
}
  

my refit client interface

public interface IHomeMonitorRestClient
{
    [Get("/Device")]
    public Task<IEnumerable<Model.Device>> Device_GetAllAsync([Authorize("Bearer")] string token);
}

my api call

var devices = await _hmRestClient.Device_GetAllAsync( await GetToken());
Peter Csala
  • 17,736
  • 16
  • 35
  • 75
jason.kaisersmith
  • 8,712
  • 3
  • 29
  • 51
  • Have you managed to make HttpClientFactory work well on MAUI? – H.A.H. Apr 05 '23 at 07:38
  • 1
    @H.A.H. Without the policy functionality then it was working fine. But I just have a small scale app used by a few people, calling the occasional simple API. So I don't know if there might be issues on a larger scale. – jason.kaisersmith Apr 05 '23 at 07:47

1 Answers1

1

In case of Polly the exact same operation is executed multiple times in case of the retry policy.

In your case that means the await GetToken() is executed only once and its value is passed to the http call which is decorated with the retry.

  • Either you can decorate both the token retrieval logic and the http call with the retry
  • Or you can use Polly's Context and a DelegatingHandler to refresh the token and set it on the request

Here I've proposed two solutions to refresh token: Refresh Token using Polly with Named Client

Peter Csala
  • 17,736
  • 16
  • 35
  • 75