如何在ASP .NET MVC 5中为AspNetUser创建SecurityStamp

当我通过Register操作创建用户时,应用程序用户运行SecurityStamp。 当我添加用户时:

if (!context.Users.Any()) { System.Diagnostics.Debug.WriteLine("INSIDE"); var hasher = new PasswordHasher(); try { var users = new List { new ApplicationUser{PasswordHash = hasher.HashPassword("TestPass44!"), Email = "informatyka4444@wp.pl", UserName = "informatyka4444@wp.pl"}, new ApplicationUser{PasswordHash = hasher.HashPassword("TestPass44!"), Email = "informatyka4445@wp.pl", UserName = "informatyka4445@wp.pl"} }; users.ForEach(user => context.Users.AddOrUpdate(user)); context.SaveChanges(); } catch (DbEntityValidationException e) { System.Diagnostics.Debug.WriteLine("EXC: "); foreach (DbEntityValidationResult result in e.EntityValidationErrors) { foreach (DbValidationError error in result.ValidationErrors) { System.Diagnostics.Debug.WriteLine(error.ErrorMessage); } } } } 

用户没有安全标记:

在此处输入图像描述

然后当我想登录时,我得到:

在此处输入图像描述

问题:如何为用户生成SecurityStamp

安全标记可以是您想要的任何内容。 它经常被误认为是时间戳,但事实并非如此。 如果用户实体上发生了某些变化,ASP.NET身份将覆盖它。 如果您直接处理上下文,最好的方法是生成一个新的Guid并将其用作图章。 这是一个简单的例子:

 var users = new List { new ApplicationUser { PasswordHash = hasher.HashPassword("TestPass44!"), Email = "informatyka4444@wp.pl", UserName = "informatyka4444@wp.pl", SecurityStamp = Guid.NewGuid().ToString() }, new ApplicationUser { PasswordHash = hasher.HashPassword("TestPass44!"), Email = "informatyka4445@wp.pl", UserName = "informatyka4445@wp.pl", SecurityStamp = Guid.NewGuid().ToString() } };