ASP.NET Core中OpenId Cookie配置持久化仍显示1969-12-31过期
我之前也碰到过一模一样的问题,折腾了好一阵子才搞明白哪里出问题了。咱们一步步拆解你的代码和问题根源:
问题根源分析
你设置了ExpireTimeSpan和全局的AuthenticationProperties.IsPersistent=true,但Cookie还是会话型(显示1969-12-31过期),主要有两个核心原因:
全局
AuthenticationProperties配置不生效
全局Configure<AuthenticationProperties>的设置不会自动应用到OpenIdConnect的登录挑战流程中。OpenIdConnect中间件在发起登录请求时,会创建独立的AuthenticationProperties实例,全局配置不会覆盖这个实例的属性。AddAzureAd可能覆盖了你的Cookie配置
AddAzureAd是微软封装的扩展方法,内部已经默认配置了Cookie认证和OpenIdConnect选项。你后面调用的AddCookie如果没有明确指定匹配的Scheme,可能不会覆盖AzureAD默认的Cookie设置。
具体解决步骤
1. 正确配置Cookie认证,确保覆盖默认设置
明确指定Cookie的Scheme(和DefaultScheme一致),确保你的配置能覆盖AzureAd的默认设置:
services.AddAuthentication(options => { options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme; options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; }) .AddAzureAd(options => Configuration.Bind("AzureAd", options)) // 明确指定Scheme,确保覆盖默认Cookie配置 .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, p => { p.ExpireTimeSpan = TimeSpan.FromDays(30); p.SlidingExpiration = true; // 可选:生产环境建议开启这些安全属性 p.Cookie.SecurePolicy = CookieSecurePolicy.Always; p.Cookie.HttpOnly = true; p.Cookie.SameSite = SameSiteMode.Strict; });
2. 在OpenIdConnect登录流程中设置持久化属性
通过OpenIdConnect的事件,在发起登录请求时明确设置IsPersistent和ExpiresUtc,这样才能让Cookie变成持久化的:
services.Configure<OpenIdConnectOptions>(OpenIdConnectDefaults.AuthenticationScheme, options => { options.Events.OnRedirectToIdentityProviderForSignIn = context => { // 强制设置持久化属性,覆盖默认会话型配置 context.Properties.IsPersistent = true; context.Properties.ExpiresUtc = DateTimeOffset.UtcNow.AddDays(30); return Task.CompletedTask; }; // 开启SaveTokens,保存ID Token和Access Token到Cookie,方便后续刷新登录状态 options.SaveTokens = true; });
3. (可选)在发起Challenge时手动传递属性
如果你的登录是通过Controller的Challenge方法触发的,也可以直接在调用时传递属性:
public IActionResult Login() { var authProps = new AuthenticationProperties { IsPersistent = true, ExpiresUtc = DateTimeOffset.UtcNow.AddDays(30) }; return Challenge(authProps, OpenIdConnectDefaults.AuthenticationScheme); }
验证效果
设置完成后,重新登录,打开Chrome调试器的Application标签,查看Cookie的过期时间,应该会显示你设置的30天后的时间,而不是1969-12-31了。
另外要注意:持久化Cookie会在浏览器关闭后保留,直到过期时间,所以要确保你的Cookie安全配置到位,避免XSS或CSRF风险。
内容的提问来源于stack exchange,提问作者Sat Thiru

