如果http请求返回401错误,我将使用polly刷新授权令牌.我的完整解决方案基于:Refresh Token using Polly with Named Client,但相关部分是:
重试策略:
static IAsyncPolicy<HttpResponseMessage> GetAuthRefreshPolicy(IServiceProvider serviceProvider)
{
return Policy<HttpResponseMessage>
.HandleResult(response => response.StatusCode == HttpStatusCode.Unauthorized)
.RetryAsync(async (handler, retry) => await serviceProvider.GetRequiredService<IAuthorisationService>().RefreshTokenAsync());
}
授权服务:
public class AuthorisationService : IAuthorisationService
{
public String? AuthToken { get; private set; }
private readonly IAuthenticationClient _AuthenticationClient;
private readonly AuthOptions _AuthOptions;
public AuthorisationService(IAuthenticationClient authenticationClient, IOptions<AuthOptions> options)
{
_AuthenticationClient = authenticationClient;
_AuthOptions = options.Value;
}
public async Task RefreshTokenAsync()
{
this.AuthToken = await _AuthenticationClient.LoginAsync(_AuthOptions.User, _AuthOptions.Password);
}
}
这在大多数情况下都工作得很好.我遇到的问题是,如果身份验证令牌当前无效,并且同时发出多个请求,因为它们是异步执行的,它们都将被无效令牌调用,失败并触发Polly重试策略,从而导致多个不必要的令牌刷新请求.
有没有办法设置Polly,以便如果请求失败并返回401,则所有后续请求都将等待,直到令牌成功刷新?或者,如果令牌已经刷新,则将重试try 排队并跳过请求新令牌?
我试着研究了Polly的隔板断路器等功能,但无法确定这些功能是否适合这个用例,或者是否有更简单的方法来锁定令牌刷新.