首页 > 解决方案 > IdentityServer 会话 cookie 不滑动

问题描述

我面临一个奇怪的问题。我可以进行静默更新,但我的 IdP cookie 正在滑动。更深入的问题...

我有一个 IdP 会话 cookie (IdentityServer) 生命周期设置为在 15 分钟内到期,并且我也为访问令牌和 id 令牌生命周期保持了相同的时间。

在我的 JavaScript 客户端上,我每 2 分钟检查一次用户活动,如果在最后 2 分钟内有活动,我将更新令牌。

我能够通过更新的过期时间获得访问令牌和 ID 令牌,但在 15 分钟(IdP cookie 生命周期)后,静默更新调用失败并且 IdP 正在注销。
我检查了静默续订呼叫的响应,我看到响应标头中没有设置 cookie(具有新的滑动到期时间)。

我应该在服务器端启用任何设置吗?感谢你的帮助。

标签: asp.net-coreasp.net-core-2.0identityserver4oidc-client-js

解决方案


正如@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>();

推荐阅读