ASP.NET Core Identity - “手动”创建用户并提供密码哈希 - 如何正确生成哈希?

Joe*_*lty 3 c# asp.net-core asp.net-core-identity

我必须手动创建用户:

var user = new User
{
    Name = "Joe",
    Email = "test@****.com",
    PasswordHash = "gdfgdfgre2132143xcxzvb=="
}

context.Users.Add(user);
Run Code Online (Sandbox Code Playgroud)

但问题是当我尝试登录该帐户时,我的密码不起作用。

复制了我知道密码的用户帐户的密码哈希,然后将其粘贴到该新用户并尝试使用相同的密码但它没有用 -password sign in failed

所以我想问 - 我这里的逻辑有什么问题,我怎样才能让它工作?

它与SecurityStamp有关吗?

Nan*_* Yu 7

如果要手动添加用户,还应设置该NormalizedUserName属性。此外,最好IPasswordHasher<TUser> Interface用于散列密码:

注入的服务:

private readonly ApplicationDbContext _context;
public readonly IPasswordHasher<IdentityUser> _passwordHasher;

public HomeController( ApplicationDbContext dbContext, IPasswordHasher<IdentityUser> _passwordHasher)
{

    this._context = dbContext;
    this._passwordHasher = _passwordHasher;

}
Run Code Online (Sandbox Code Playgroud)

我假设你User继承IdentityUser,在这里我使用IdentityUser例如:

IdentityUser applicationUser = new IdentityUser();
Guid guid = Guid.NewGuid();
applicationUser.Id = guid.ToString();
applicationUser.UserName = "Joe";
applicationUser.Email = "wx@hotmail.com";
applicationUser.NormalizedUserName = "wx@hotmail.com";

_context.Users.Add(applicationUser);


var hashedPassword = _passwordHasher.HashPassword(applicationUser, "YourPassword");
applicationUser.SecurityStamp = Guid.NewGuid().ToString();
applicationUser.PasswordHash = hashedPassword;

_context.SaveChanges();
Run Code Online (Sandbox Code Playgroud)

您还可以使用UserManager.CreateAsync给定的密​​码在后备存储中创建指定的用户:

var user = new IdentityUser { UserName = "Joe", Email = "wx@hotmail.com" };
var result = await _userManager.CreateAsync(user, "YourPassWord");
if (result.Succeeded)
{

}
Run Code Online (Sandbox Code Playgroud)

注意:您应该Email在登录时提供值。