正如@mackie 在评论中提到的那样,cookie 只有在过期的一半时才会滑动......这与 Identity Server 无关,而是.NET 框架
我能够通过这样做来克服它:
public class CustomCookieOptions : IConfigureNamedOptions<CookieAuthenticationOptions>
{
private readonly AppConfiguration _appConfiguration;
private const string UTC_DATE_TIME_FORMAT = "r";
private const string EXPIRES_KEY = ".expires";
public CustomCookieOptions(IOptions<AppConfiguration> appConfiguration)
{
_appConfiguration = appConfiguration.Value;
}
public void Configure(CookieAuthenticationOptions options)
{
}
public void Configure(string name, CookieAuthenticationOptions options)
{
options.Events.OnValidatePrincipal = context =>
{
if (context.Principal.Identity.IsAuthenticated &&
options.Cookie.Name == IdentityServerConstants.DefaultCookieAuthenticationScheme)
{
if (context.Properties.Items.ContainsKey(EXPIRES_KEY)
&& context.Request.Path.Value.StartsWith("/connect/authorize"))
{
var expiresAt = DateTimeOffset.Parse(context.Properties.Items[EXPIRES_KEY]);
if (DateTimeOffset.UtcNow <= expiresAt)
{
context.ShouldRenew = true;
context.Properties.Items[EXPIRES_KEY] =
DateTimeOffset.UtcNow.AddSeconds(_appConfiguration.CookieLifetimeInSeconds)
.ToString(UTC_DATE_TIME_FORMAT, CultureInfo.InvariantCulture);
}
}
}
return Task.CompletedTask;
};
}
然后注册它:
services.AddSingleton<IConfigureOptions<CookieAuthenticationOptions>, CustomCookieOptions>();