.NET Identity中SecurityStampValidator引发自动登出问题求助
要彻底取消SecurityStampValidator的身份校验逻辑,只靠Cookie过期时间维持登录状态,按以下步骤操作:
1. 移除SecurityStampValidator的绑定
你的代码里仍通过SecurityStampValidator.OnValidateIdentity绑定了校验逻辑,哪怕validateInterval设得极长,在.NET 6+环境下仍可能触发隐性校验。直接替换或清空这个委托:
app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString("/Account/Login"), ExpireTimeSpan = TimeSpan.FromDays(500), Provider = new CookieAuthenticationProvider() { // 完全跳过SecurityStamp校验,直接标记身份有效 OnValidateIdentity = context => { context.OwinContext.Authentication.SignIn(context.Properties, context.Identity); return Task.CompletedTask; } } });
2. 让UserManager彻底禁用SecurityStamp支持
在CustomUserManager中重写属性并屏蔽相关方法,确保框架不会尝试读取或更新SecurityStamp:
public class CustomUserManager : UserManager<CustomUser, int> { public override bool SupportsUserSecurityStamp => false; // 覆盖SecurityStamp相关方法,避免框架调用出错 public override Task<string> GetSecurityStampAsync(int userId) { return Task.FromResult(string.Empty); } public override Task<IdentityResult> UpdateSecurityStampAsync(int userId) { return Task.FromResult(IdentityResult.Success); } }
3. 登录时开启Cookie持久化
调用登录方法时,必须将isPersistent设为true,否则Cookie是会话级的,浏览器关闭后自动失效:
var result = await SignInManager.PasswordSignInAsync(model.UserName, model.Password, isPersistent: true, lockoutOnFailure: false);
4. 排查.NET 6+服务器环境差异
相同代码在.NET 4.5正常但.NET 6+出问题,需额外检查:
- 机器密钥一致性:如果是集群服务器,确保所有节点使用相同的机器密钥,否则Cookie加密解密会失败导致身份失效。
- Cookie属性配置:若应用跨域/跨子域名,需设置
SameSite属性(如SameSiteMode.None)并启用HTTPS。
完成以上操作后,用户登录状态将完全由Cookie过期时间控制,不会再因SecurityStamp校验被强制登出。
内容的提问来源于stack exchange,提问作者mhenrickson
相关产品推荐
相关产品推荐

