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

时间:2019-10-01 07:48:07

标签: c# asp.net-core asp.net-core-identity

我必须手动创建用户:

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

context.Users.Add(user);

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

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

所以我想问-这里的逻辑有什么问题以及如何使它起作用?

它与SecurityStamp有关吗?

1 个答案:

答案 0 :(得分:2)

如果要手动添加用户,还应该设置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;

}

我假设您的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 hasedPassword = _passwordHasher.HashPassword(applicationUser, "YourPassword");
applicationUser.SecurityStamp = Guid.NewGuid().ToString();
applicationUser.PasswordHash = hasedPassword;

_context.SaveChanges();

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

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

}

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