首页 > 解决方案 > 如何在 .Net Core 3.1 Identity Server 4 中更改持久性 Cookie 过期时间

问题描述

我正在使用 .Net Core 3.1 和 Identity server 4,想要更改持久性 cookie 过期时间。为此,在 Startup.cs 中使用以下代码

services.ConfigureApplicationCookie(options =>
{
     options.ExpireTimeSpan = TimeSpan.FromMinutes(5);
});

有与“isPersistent”绑定的“Stay Singed In”复选框。使用上述代码,如果 SignIn 使用“isPersistent=true”,则 Cookie 将在 5 分钟后过期,并且可以在浏览器 cookie 中看到 在此处输入图像描述

如果浏览器中的“isPersistent=false”cookie 如下所示 在此处输入图像描述

但在“isPersistent=false”的情况下,cookie 也会在 5 分钟后过期,这不应该。我通过刷新页面检查,它重定向到登录页面。

如果不使用该代码,则“isPerstent=false”工作正常。我只想更改 Persistent Cookie 的过期时间。请帮忙

标签: c#.net-coreidentityserver4identity.net-core-3.1

解决方案


这是我的解决方案。需要覆盖“SignInWithClaimsAsync”,如下所示

public override async Task SignInWithClaimsAsync(ApplicationUser user, AuthenticationProperties authenticationProperties, System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> additionalClaims)
{
    if (authenticationProperties != null && authenticationProperties.IsPersistent)
    {
        authenticationProperties.ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(30); // for 30 mins
    }

    await base.SignInWithClaimsAsync(user, authenticationProperties, additionalClaims);
}

推荐阅读