ASP.NET Core Cookie过期设置未生效,认证中间件是否验证过期?
我将Cookie过期时间设置为120秒,但超过该时间后,系统仍显示我处于授权状态。ASP.NET Core认证中间件是否实际验证Cookie是否过期?
Program.cs配置代码
builder.Services.AddAuthentication(options => { options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme; }) .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options => { options.ExpireTimeSpan = TimeSpan.FromSeconds(120); }) .AddOpenIdConnect( OpenIdConnectDefaults.AuthenticationScheme, options => { options.Authority = builder.Configuration["InteractiveServiceSettings:AuthorityUrl"]; options.ClientId = builder.Configuration["InteractiveServiceSettings:ClientId"]; options.ClientSecret = builder.Configuration["InteractiveServiceSettings:ClientSecret"]; options.ResponseType = "code"; options.Scope.Clear(); options.Scope.Add("openid"); options.Scope.Add("profile"); options.Scope.Add("offline_access"); options.Scope.Add("ExtrenalAPI.read"); options.SaveTokens = true; options.GetClaimsFromUserInfoEndpoint = true; } ); var app = builder.Build(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); app.Run();
控制器代码
我使用带有[Authorize]属性的ShopsController,120秒后仍能发起请求,原本预期会被重定向到登录页:
[Authorize] public class ShopsController : Controller { public IActionResult Index() { return View(shops); } }
Identity Server客户端配置
public static IEnumerable<Client> Clients => new[] { new Client { ClientId = "mvc", ClientSecrets = { new Secret("mvc1".Sha256()) }, AllowedGrantTypes = GrantTypes.Code, RedirectUris = { "https://localhost:5446/signin-oidc" }, FrontChannelLogoutUri = "https://localhost:5446/signout-oidc", PostLogoutRedirectUris = { "https://localhost:5446/signout-callback-oidc" }, AllowOfflineAccess = true, AllowedScopes = { "openid", "profile", "ExtrenalAPI.read" } } };
问题原因
ASP.NET Core的Cookie认证中间件确实会验证Cookie过期时间,但你的配置存在几个关键点导致过期逻辑未触发:
- 滑动过期默认开启:
SlidingExpiration默认值为true,只要用户在过期时间窗口的一半内发起请求,Cookie的过期时间就会自动续期,120秒内有操作就不会过期。 - 未设置Cookie绝对过期时间:仅配置
ExpireTimeSpan而未设置Cookie.MaxAge,结合滑动过期,Cookie会被持续续期。 - Refresh Token自动刷新:由于请求了
offline_accessScope,客户端保存了refresh_token,当Cookie过期时,中间件会自动用refresh_token获取新的id_token,重新签发Cookie维持登录状态。
解决方法
根据需求调整配置:
1. 强制Cookie120秒后过期(禁用滑动过期)
修改Cookie认证配置,关闭滑动过期并设置Cookie绝对最大存活时间:
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options => { options.ExpireTimeSpan = TimeSpan.FromSeconds(120); options.SlidingExpiration = false; // 禁用滑动过期,到期立即失效 options.Cookie.MaxAge = TimeSpan.FromSeconds(120); // 设置Cookie绝对过期时间 })
2. 限制Refresh Token的自动续期
如果不需要自动续期,可在Identity Server客户端配置中限制refresh_token的生命周期:
new Client { // 原有配置... RefreshTokenExpiration = TokenExpiration.Absolute, AbsoluteRefreshTokenLifetime = 120, // refresh_token 120秒后过期 RefreshTokenUsage = TokenUsage.OneTimeOnly // 可选,refresh_token仅能使用一次 }
3. 确认中间件顺序
当前代码中UseAuthentication()在UseAuthorization()之前,顺序正确,无需调整。
验证方式
修改配置后,等待120秒不进行任何操作,再发起请求,此时应被重定向到登录页。也可通过浏览器开发者工具查看Cookie的Expires或Max-Age属性,确认是否设置为120秒后过期。
内容的提问来源于stack exchange,提问作者west
相关产品推荐
相关产品推荐

