我目前正在使用DelegatingHandler来检查请求是否在发送到我们的 Web API 时变得未经授权。如果响应确实未经授权,我目前正在发送刷新令牌以重新登录用户,然后使用新的访问令牌更新以下请求。我遇到的问题是,许多调用是异步的,并且在其他调用完成之前继续,并且刷新令牌代码被多次命中导致多个刷新令牌被更新/保存。处理这种情况的最佳方法是什么?我当前的处理程序看起来像这样..
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;
}
}
我不确定使用处理程序是最佳实践还是理想。我认为最好检查每个请求,以防访问令牌在调用过程中变得无效。使用刷新令牌时推荐的方法是什么?我还使用 DelegatingHandler 重试失败的请求 2 次,但身份验证处理程序是 HttpClient 管道中的最后一个处理程序。非常感谢任何建议!