asp.net-core - IdentityServer 会话 cookie 不滑动
问题描述
我面临一个奇怪的问题。我可以进行静默更新,但我的 IdP cookie 正在滑动。更深入的问题...
我有一个 IdP 会话 cookie (IdentityServer) 生命周期设置为在 15 分钟内到期,并且我也为访问令牌和 id 令牌生命周期保持了相同的时间。
在我的 JavaScript 客户端上,我每 2 分钟检查一次用户活动,如果在最后 2 分钟内有活动,我将更新令牌。
我能够通过更新的过期时间获得访问令牌和 ID 令牌,但在 15 分钟(IdP cookie 生命周期)后,静默更新调用失败并且 IdP 正在注销。
我检查了静默续订呼叫的响应,我看到响应标头中没有设置 cookie(具有新的滑动到期时间)。
我应该在服务器端启用任何设置吗?感谢你的帮助。
解决方案
正如@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>();
推荐阅读
- python - Jupyter Notebook 错误:元组索引超出范围
- java - 每当单击按钮和编辑文本为空或填充除 url 以外的短字母时,应用程序就会崩溃
- sql - 使用查询插入 MS-Access 关系数据库的最佳方法
- reactjs - 新部署后 create-react-app 崩溃
- reactjs - 增加超时限制 gatsby-source-wordpress-experimental
- python - 使用 Django 更新数据库时遇到问题
- python - 我如何获得不和谐消息的作者,然后给他发私信?
- php - 在 laravel 7 中使用“barryvdh/laravel-dompdf”:“^0.8.7”找不到图像或输入未知
- javascript - 使用 ajax 在 codeigniter 中按特定 id 查看模态中的完整数据
- python - 将可变长度参数传递给具有可变数量占位符的格式化字符串