I'm currently using a DelegatingHandler to check requests if they become Unauthorized when sending to our Web API. If the response does become unauthorized, I'm currently sending a refresh token to log the user back in and then updating the following requests with the new access token. The issue that I'm running into, is that many of the calls are asynchronous and continue on before the other ones finish and the refresh token code is hit multiple times cause multiple refresh tokens to be updated/saved. What is the best way to handle this scenario? My current Handler looks like this..
public class AuthenticationHandler : DelegatingHandler
{
private AccountRepository _accountRepo;
private string _originalAuthToken = String.Empty;
private const int _maxRefreshAttempts = 1;
public AuthenticationHandler() : this(new HttpClientHandler())
{
_accountRepo = new AccountRepository();
}
protected AuthenticationHandler(HttpMessageHandler innerHandler) : base(innerHandler)
{
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
HttpResponseMessage response = new HttpResponseMessage();
request = CheckForAuthToken(request);
response = await base.SendAsync(request, cancellationToken);
if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
{
for (int i = 1; i == _maxRefreshAttempts; i++)
{
response = await _accountRepo.SignInWithRefreshToken();
if (response.IsSuccessStatusCode)
{
request = CheckForAuthToken(request);
response = await base.SendAsync(request, cancellationToken);
}
}
}
return response;
}
private HttpRequestMessage CheckForAuthToken(HttpRequestMessage request)
{
if (App.CurrentLoggedInUser != null)
{
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", App.CurrentLoggedInUser.AccessToken);
}
return request;
}
}
I'm not sure if using a handler is best practice or ideal. I thought it would be nice to check every request just incase the access token becomes invalid during the call itself. What is the recommended approach when using refresh tokens? I am also using a DelegatingHandler to retry failed requests 2 times but the Authentication Handler is the last handler in the HttpClient pipeline. Any suggestions is greatly appreciated!