我将 Refit 库与我的 Xamarin 表单项目一起使用来发送 API 请求。它工作得很好,但是当访问令牌过期时会出现问题。
当访问令牌过期时,我从服务器收到 401 错误,正如预期的那样。然后我调用 Identity Server 以发出新的访问令牌,但我在重新提交 API 请求时遇到了困难。我仍然收到未经授权的错误。感谢一些帮助。
我创建了一个 AuthenticatedHttpClientHandler 类来处理令牌。
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;
}
}
}