Ale*_*tos 2 asp.net-core identityserver4 asp.net-core-identity
我正在将数以万计的用户从数据库中没有密码的旧网站迁移到这个新的 Web 应用程序,但是,当我尝试使用异步方法导入用户时,最终需要几天的时间几天后我最终取消了它。
现在我已经求助于直接从 _context.Users.Add 创建新用户并分配他们的角色,我可以毫无问题地做到这一点..但是,我似乎无法弄清楚如何创建通用密码(都是一样的)密码),因为这些用户只会获得一个密码来观看直播(不需要超级安全),但我仍然需要管理员帐户的安全部分,通过客户端/管理员端 UI 处理其他内容。如果用户登录,我会自动为他们输入默认密码。
但由于某种原因,我无法让密码哈希器正常工作,因为当我登录时,它说密码错误......
这就是我用来生成密码和创建用户的...
var appUser = new ApplicationUser() {
Id = GenerateId(),
AccessFailedCount = 0,
Email = user[1],
PasswordHash = "",
FullName = "Standard User",
UserName = user[1],
PhoneNumber = user[8],
FirstName = user[2],
LastName = user[3],
JoinMailingList = user[4],
Country = user[5],
City = user[6],
StateRegion = user[7]
};
_context.Users.Add(appUser);
var options = new PasswordHasherOptions();
options.CompatibilityMode = PasswordHasherCompatibilityMode.IdentityV2;
var hasher = new PasswordHasher < ApplicationUser > ();
appUser.PasswordHash = hasher.HashPassword(appUser, "Default8!");
var role = _context.Roles.FirstOrDefault(r => r.Name == "user");
if (role != null) {
var userRole = new IdentityUserRole < string > ();
userRole.RoleId = role.Id;
userRole.UserId = appUser.Id;
_context.UserRoles.Add(userRole);
}
}
_context.SaveChanges();
Run Code Online (Sandbox Code Playgroud)
任何人都可以帮助我解决如何散列密码以存储到数据库中的问题吗?
如果用户登录,我会自动为他们输入默认密码。
如果您使用 .net core Identity,则可以使用UserManager.CreateAsync在后备存储中使用给定密码创建指定用户:
public virtual System.Threading.Tasks.Task<Microsoft.AspNetCore.Identity.IdentityResult> CreateAsync (TUser user, string password);
Run Code Online (Sandbox Code Playgroud)
以下代码供您参考:
var user = new ApplicationUser { UserName = "wx2@hotmail.com", Email = "wx2@hotmail.com" };
var result = await _userManager.CreateAsync(user, "YourPassWord");
if (result.Succeeded)
{
}
Run Code Online (Sandbox Code Playgroud)
身份系统将帮助创建密码哈希并存储在数据库中。如果您仍然需要手动散列密码,请参阅IPasswordHasher 接口。
编辑 :
如果您想直接插入/通过数据库上下文更新,你应该设置正确NormalizedUserName,并SecurityStamp让系统工作:
ApplicationUser applicationUser = new ApplicationUser();
Guid guid = Guid.NewGuid();
applicationUser.Id = guid.ToString();
applicationUser.UserName = "wx@hotmail.com";
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();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6958 次 |
| 最近记录: |