在具有 ASP.NET Identity 的 ASP.NET Core 1.1 应用程序上,我创建了一个用户:
PasswordHasher<User> hasher = new PasswordHasher<User>();
User user = new User {
Email = "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="86ece9eee8c6e5e9ebf6e7e8ffa8e5e9eb" rel="noreferrer noopener nofollow">[email protected]</a>",
Username = "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b1dbded9dff1d2dedcc1d0dfc89fd2dedc" rel="noreferrer noopener nofollow">[email protected]</a>
};
user.PasswordHash = hasher.HashPassword(user, "johnpass");
context.Users.Add(user);
context.SaveChanges();
用户已创建,但当我尝试使用以下内容进行签名时失败:
SignInResult result = await _signInManager.PasswordSignInAsync("<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="442e2b2c2a04272b2934252a3d6a272b29" rel="noreferrer noopener nofollow">[email protected]</a>", "johnpass", false, true);
然后我尝试使用 UserManager 创建用户:
PasswordHasher<User> hasher = new PasswordHasher<User>();
User user = new User {
Email = "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1c767374725c7f73716c7d7265327f7371" rel="noreferrer noopener nofollow">[email protected]</a>",
Username = "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="80eaefe8eec0e3efedf0e1eef9aee3efed" rel="noreferrer noopener nofollow">[email protected]</a>
};
await userManager.CreateAsync(user, "johnpass");
现在我可以登录了。问题似乎出在 HashPassword 方法上。
有人知道如何在没有 UserManager 的情况下创建用户吗?
更新
我尝试在不依赖注入(inject)的情况下创建 UserManager,因为我是在控制台应用程序而不是 Web 应用程序上创建测试数据:
var userStore = new UserStore(Context);
var userManager = new UserManager<User>(userStore, null, null, null, null, null, null, null, null);
用户已创建,但我仍然无法登录。
最佳答案
您必须执行以下操作:
userManager.UpdateSecurityStampAsync(domainUser);
domainUser.NormalizedUserName = domainUser.NormalizedEmail = domainUser.UserName = domainUser.Email;
await userManager.UpdateNormalizedUserNameAsync(domainUser);
await userManager.UpdateNormalizedEmailAsync(domainUser);
await userManager.UpdateAsync(domainUser);
如果您在配置中设置了电子邮件确认
var token = await userManager.GenerateEmailConfirmationTokenAsync(domainUser);
await userManager.ConfirmEmailAsync(domainUser, token);
关于c# - 在 Asp.Net Core Identity 中创建没有 UserManager 的用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42862297/