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());