我正在尝试创建 RevalidatingServerAuthenticationStateProvider 来检查 ClaimsPrincipal 是否已过期。
我已经创建了它的实现(TokenExpiryAuthStateProvider)并将其注册到ConfigureServices 中,但构造函数从未被调用,ValidateAuthenticationStateAsync 也未被调用。(我也尝试了实现工厂来注册它,结果相同)
我将 AuthStateProvider 注入到 MainLayout 中以查看注入的内容,但它仍在注入 ServerAuthenticationStateProvider。我究竟做错了什么?
我的实现从未被调用:
public class TokenExpiryAuthStateProvider : RevalidatingServerAuthenticationStateProvider
{
protected override TimeSpan RevalidationInterval => TimeSpan.FromSeconds(10);
public TokenExpiryAuthStateProvider(ILoggerFactory logger) : base(logger)
{
}
protected override Task<bool> ValidateAuthenticationStateAsync(AuthenticationState authenticationState, CancellationToken cancellationToken)
{
DateTime expiry = authenticationState.User.GetExpiryDate();
if (expiry < DateTime.UtcNow)
return Task.FromResult(false);
else
return Task.FromResult(true);
}
}
Run Code Online (Sandbox Code Playgroud)
配置服务
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<HttpClientFactory>();
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie();
services.ConfigureApplicationCookie(options =>
{
options.Cookie.HttpOnly = true;
options.SlidingExpiration = true;
options.ExpireTimeSpan = TimeSpan.FromMinutes(5);
});
services.AddScoped<AuthenticationStateProvider, …Run Code Online (Sandbox Code Playgroud)