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

问题描述 投票:0回答:1

我必须手动创建用户:

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

context.Users.Add(user);

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

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

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

与SecurityStamp有关吗?

c# asp.net-core asp.net-core-identity
1个回答
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 = "[email protected]";
applicationUser.NormalizedUserName = "[email protected]";

_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 = "[email protected]" };
var result = await _userManager.CreateAsync(user, "YourPassWord");
if (result.Succeeded)
{

}

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

© www.soinside.com 2019 - 2024. All rights reserved.