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;
}
}
}
Generating an API tokenClick the Settings tab, and make sure Token Access is enabled. Click the Add API token button to the right of Active API Tokens. The token is generated and displayed. Enter an API token description.
Step 1 − First, the client authenticates with the authorization server by giving the authorization grant. Step 2 − Next, the authorization server authenticates the client, validates the authorization grant and issues the access token and refresh token to the client, if valid.
I would suggest inspecting the raw request sent to see if the one sent after refresh token has the proper headers sent.
There is also the chance that you are sending the wrong token on the second try. Confirm that the value in newToken
is what is being used via Settings.AccessToken
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With