我正在使用 ASP.NET Identity。当我阻止用户帐户时,它应该立即注销。 这是我的代码:
await UserManager.SetLockoutEnabledAsync(user.Id, true);
await UserManager.SetLockoutEndDateAsync(user.Id,DateTime.Today.AddYears(10));
await UserManager.UpdateSecurityStampAsync(user.Id);
并在
Startup.Auth.cs
:
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<AppUserManager, ApplicationUser>(
validateInterval: TimeSpan.FromSeconds(0),
regenerateIdentity: (manager, user) => manager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie))
}
});
但它不会注销用户。我做错了什么?
为什么不使用
AuthenticationManager.SignOut()
?
var authenticationManager= HttpContext.GetOwinContext().Authentication;
authenticationManager.SignOut();
身份验证与 cookie 连接,并且 经过身份验证的信息保存在该 cookie 中。该 cookie 在您设置的时间内有效,无论您做什么此 cookie 都会使用户保持登录状态,直到过期或从浏览器中删除。
您可以从用户浏览器中删除该 cookie,但如果由于某种原因他保留该 cookie,则仍然可以登录,直到 cookie 过期。因此,如果您的用户已经通过身份验证,直到 cookie 过期才实际登录。
如果您希望立即注销,您需要进行一些检查可能不时使用ajax,如果您的页面使用ajax,或检查每个页面调用上用户的身份验证,或在数据库上创建一些其他表来保存身份验证cookie,并标记那些不再有效的表,并对每个调用进行检查。
很抱歉,我没有代码可以向您展示,这是一个复杂的问题,需要您进行设计以满足您的需求和程序
这是我的解决方案:
不要调用
UserManager.UpdateSecurityStampAsync(userId)
,而是手动设置安全标记并注销用户。
public void UpdateSecurityStamp(string userId)
{
using (var db = new ApplicationDbContext())
{
var user = db.Users.FirstOrDefault(x => x.Id.Equals(userId));
if (user != null)
{
user.SecurityStamp = Convert.ToString(Guid.NewGuid());
db.SaveChanges();
}
}
}
我必须将其添加到 Program.cs 中作为
的另一个选项builder.Services.PostConfigure<CookieAuthenticationOptions>(IdentityConstants.ApplicationScheme, options =>
{
options.Events.OnValidatePrincipal = async context =>
{
if (!(context.Principal?.Identity is ClaimsIdentity claimIdentity)) return;
var mgr = context.HttpContext.RequestServices.GetRequiredService<SignInManager<ApplicationUser>>();
var user = await mgr.UserManager.FindByNameAsync(claimIdentity.Name);
if (user != null && claimIdentity.Claims.FirstOrDefault(c => c.Type == "AspNet.Identity.SecurityStamp")?.Value == await mgr.UserManager.GetSecurityStampAsync(user))
{
}
else
{
context.RejectPrincipal();
await mgr.SignOutAsync();
}
};
});
但是回想起来,似乎有点没有必要通过安全印章,如果我再次这样做,我会为用户添加一个 IsDisabled 标志,然后检查一下..