Polly: Refresh Authorization Code on When.All (causing multiple refresh authentications)
What are you wanting to achieve?
I am trying to refresh an expired authentication code whilst also ensuring that the refreshing authentication code block is not called repeated times for every fail.
In our application we use Task.WhenAll that will fire multiple requests, if all requests should fail due to Unauthorized then the AuthEnsuringPolicy executes which is currently being called multiple times which is not ideal.
What code or approach do you have so far?
I followed this example to use the Context and it works fine when making single requests. The issues starts happening for multiple requests such as using Task.WhenAll for sending multiple http requests, the Polly Policy is called for every fail resulting in many attempts to refresh code, it would be better if we can cancel other attempts to refresh code on first entering the code block and then retry all requests again once a successful refresh was achieved on the first attempt. Can this be done?
So far my code is:
public static AsyncRetryPolicy<HttpResponseMessage> AuthEnsuringPolicy = Policy<HttpResponseMessage>
.HandleResult(r => r.StatusCode == HttpStatusCode.Unauthorized)
.RetryAsync(1, onRetryAsync: async (ex, i, context) =>
{
Debug.WriteLine("Unauthorized request, refreshing token.");
IUserManagementService userManagementService = App.ContainerProvider.Resolve<IUserManagementService>();
ILocalStorageService localStorageService = App.ContainerProvider.Resolve<ILocalStorageService>();
HttpClient httpClient = (HttpClient)context["httpClient"];
CancellationTokenSource cancellationTokenSource = (CancellationTokenSource)context["cancellationTokenSource"];
cancellationTokenSource.Cancel();
if (localStorageService.GetCustomer() is Customer customer && await customer.GetPasswordAsync().ConfigureAwait(true) is string password && await userManagementService.RefreshAuthorizationTokenAsync(customer.Mobile, password).ConfigureAwait(true) is not null)
{
if (await localStorageService.GetSecurityTokenAsync().ConfigureAwait(false) is string securityToken && !string.IsNullOrEmpty(securityToken))
{
if (httpClient.DefaultRequestHeaders.Contains(Constants.AuthenticationTokenHeaderKey))
{
_ = httpClient.DefaultRequestHeaders.Remove(Constants.AuthenticationTokenHeaderKey);
}
httpClient.DefaultRequestHeaders.Add(Constants.AuthenticationTokenHeaderKey, securityToken);
}
}
});
Also we setup like this:
IAsyncPolicy<HttpResponseMessage> wrapOfRetryAndFallback = Policy.WrapAsync(Policy.HandleResult<HttpResponseMessage>(r => !r.IsSuccessStatusCode).FallbackAsync(fallbackAction, onFallBackAsync), PollyPolicies.AuthEnsuringPolicy);
_ = containerRegistry.RegisterSingleton<IHttpClientFactory>(() => new ServiceCollection().AddHttpClient(Constants.HttpClientWithRetry).AddPolicyHandler(wrapOfRetryAndFallback).Services.BuildServiceProvider().GetService<IHttpClientFactory>());
Usage:
CancellationTokenSource _policyCTS = new();
requestMessage.SetPolicyExecutionContext(new Context
{
{ "retrycount", 0 },
{ "httpClient", httpClient },
{ "cancellationTokenSource", _policyCTS }
});
HttpResponseMessage httpResponseMessage = await httpClient.SendAsync(requestMessage, _policyCTS.Token).ConfigureAwait(false);
Additional context
Initially I thought we could use the CancellationTokenSource somewhere but not to sure.
About this issue
- Original URL
- State: closed
- Created 3 years ago
- Comments: 15 (8 by maintainers)
@peter-csala this might take some time to get you a sample application, but Ill endeavor to get this ASAP. Keen to get this sorted.
I will try get a sample application shortly. Thank you!
@peter-csala sorry for my own delay in responding, many tasks I am across and put this issue back a bit but I will check this out shortly and get back to you if I can find further information on this. Will be in touch shortly.