当我通过注册操作创建用户时,当应用程序正在运行时,应用程序user获取SecurityStamp。当我添加用户时:
if (!context.Users.Any()) {
System.Diagnostics.Debug.WriteLine("INSIDE");
var hasher = new PasswordHasher();
try {
var users = new List<ApplicationUser> {
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
?
发布于 2014-08-18 16:55:12
安全戳可以是你想要的任何东西。它经常被误认为是时间戳,但事实并非如此。如果用户实体发生变化,它将被ASP.NET标识覆盖。如果您直接处理上下文,最好的方法是生成一个新的Guid并将其用作戳记。下面是一个简单的例子:
var users = new List<ApplicationUser>
{
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()
}
};
发布于 2020-05-26 10:14:15
如果我们查看IdentityUser
表AspNetUsers
数据,我们将看到SecurityStamp
具有与普通GUID
不同的形式
这是因为GUID
被转换为十六进制映射字符串。
我们可以创建一个函数来生成新的安全戳,它将生成一个新的GUID
并将其转换为十六进制映射字符串:
Func<string> GenerateSecurityStamp = delegate()
{
var guid = Guid.NewGuid();
return String.Concat(Array.ConvertAll(guid.ToByteArray(), b => b.ToString("X2")));
};
你可以检查它在这个.NET Fiddle上运行。
因此,如果我们想要为身份用户设定种子,我们可以使用它来生成SecurityStamp
modelBuilder.Entity<IdentityUser>().HasData(new ApplicationUser
{
...
// Security stamp is a GUID bytes to HEX string
SecurityStamp = GenerateSecurityStamp(),
});
Warning:要非常小心,不要使用上面的示例作为种子,因为它会在我们每次创建新迁移时更改数据。在使用HasData
时,种子设定数据应始终预先生成,而不是动态内联生成。
https://stackoverflow.com/questions/25355536
复制相似问题