c# - ASP.NET Core Identity - 创建用户 "manually"并提供密码哈希 - 如何正确生成哈希?

标签 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有关吗?

最佳答案

如果要手动添加用户,还应设置 NormalizedUserName属性(property) 。另外,最好使用IPasswordHasher<TUser> Interface对于散列密码:
注入(inject)的服务:

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 hashedPassword = _passwordHasher.HashPassword(applicationUser, "YourPassword");
applicationUser.SecurityStamp = Guid.NewGuid().ToString();
applicationUser.PasswordHash = hashedPassword;

_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登录时的值。

关于c# - ASP.NET Core Identity - 创建用户 "manually"并提供密码哈希 - 如何正确生成哈希?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58180234/

相关文章:

c# - identitysever和AspNetUsers

c# - 如何使用DotNetBrowser填写用户名和密码

c# - DataGridView 更改符合另一个单元格条件的单元格内容

c# - 如何在与 NHibernate 的一对多关系中映射枚举?

c# - 此应用程序只能在应用程序容器的上下文中运行

asp.net-core - 存储在 key 保管库中时未拾取 InstrumentationKey

c# - 如何确定 .net 应用程序是否为 "core"应用程序?

c# - LINQ根据计数> 1的另一列获取列

asp.net-core - 在 asp.net 核心标识中更改电子邮件异步 "invalid token"

c# - 实现 SendEmailAsync 接口(interface)并发送邮件