在锁定用户的同时,我还更改了 SecurityStamp,这将导致 auth cookie 无效。可以在 Startup.Auth 中找到的集成身份 2.0 机制每隔(默认:30 分钟)检查 cookie 完整性,如果无效(例如,具有不同 SecurityStamp 的 cookie),则注销用户。检查的时间延迟可以更改,但我认为它适合我的项目。
这部分代码使一些用户的 cookie 无效,我每天安排一些检查,如果为真,就会触发它;
var userManager = Request.GetOwinContext().GetUserManager<ApplicationUserManager>();
var user = userManager.FindByName(username);
userManager.SetLockoutEnabled(user.Id, true);
userManager.SetLockoutEndDate(user.Id, DateTime.MaxValue);
user.SecurityStamp = Guid.NewGuid().ToString("D");
userManager.UpdateSecurityStamp(user.Id);
负责 cookie 验证和/或重新生成的部分已经存在,但如果我没记错的话,它只存在于 Identity 2.0 中。它的配置在 Startup.Auth.cs 文件中,看起来像这样:
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
// Enables the application to validate the security stamp when the user logs in.
// This is a security feature which is used when you change a password or add an external login to your account.
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
}
});
我在 stackoverflow 上的不同文章中找到了所有这些内容,因此归功于这些人。
Kevin Raffay 的回答肯定有效,所以我将其标记为答案,因为我是新手,我不确定哪种方法更好。