I am using the Refit library with my Xamarin forms project to send API requests. It works great, but have an issue when the access token expires.
When the access token expires, I get an 401 error from the server, as expected. I then make a call to the Identity Server to issue a new access token, but I am having difficulty in resubmitting the API request. I still get unauthorised error. Appreciate some help.
I have created an AuthenticatedHttpClientHandler class to handle the token.
public class AuthenticatedHttpClientHandler : HttpClientHandler { private readonly string _token; public AuthenticatedHttpClientHandler(string token ) { _token = token; } protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var auth = request.Headers.Authorization; if (auth != null && !string.IsNullOrWhiteSpace(_token)) { request.Headers.Authorization = new AuthenticationHeaderValue(auth.Scheme, _token); } else { request.Headers.Remove("Authorization"); } var result = await base.SendAsync(request, cancellationToken).ConfigureAwait(false); if (result.StatusCode == System.Net.HttpStatusCode.Unauthorized ) { IdSrvApiService idsrvApiService = new IdSrvApiService(); RefreshTokenService refreshTokneService = new RefreshTokenService(idsrvApiService); if( Settings.RefreshToken != ""){ var newToken = await refreshTokneService.RefreshAccessToken(Priority.Background).ConfigureAwait(false); TokenHelper.CacheToken(newToken); request.Headers.Authorization = new AuthenticationHeaderValue(auth.Scheme, Settings.AccessToken); return await base.SendAsync(request, cancellationToken).ConfigureAwait(false); } else { return result; } } else { return result; } } }
newTokenis what is being used viaSettings.AccessToken