无法从PasswordHasher登录种子的自定义IdentityUser
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了无法从PasswordHasher登录种子的自定义IdentityUser相关的知识,希望对你有一定的参考价值。
我在上下文OnModelCreating方法中创建了用户。当我尝试使用给定的密码登录时,它总是失败。
我也尝试过使用UserManager创建新帐户,它的作用就像一个超级按钮。
我认为问题出在PasswordHasher中。
上下文类
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
var unconfirmedUser = new AppUser
{
Id = 2,
UserName = "00001",
Identifier = "00001",
FirstName = "TestName",
LastName = "TestLastName",
NormalizedUserName = "TestAccount1",
SecurityStamp = Guid.NewGuid().ToString(),
LockoutEnabled = true
};
unconfirmedUser.PasswordHash = new PasswordHasher<AppUser>()
.HashPassword(unconfirmedUser, "f1fRlQ9c&i72yI_2ApLT");
builder.Entity<AppUser>().HasData(unconfirmedUser); ;
}
Controller
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginModel model, string returnUrl = null)
{
returnUrl = returnUrl ?? Url.Content("~/");
if (ModelState.IsValid)
{
var result = await SignInManager.PasswordSignInAsync(model.Identifier, model.Password,
false, lockoutOnFailure: true);
if (result.Succeeded)
{
Logger.LogInformation($"User: [{model.Identifier}] logged in.");
return LocalRedirect(returnUrl);
}
if (result.IsLockedOut)
{
Logger.LogWarning($"User account: [{model.Identifier}] locked out.");
return RedirectToAction("Lockout", "Account");
}
else
{
ModelState.AddModelError(string.Empty, "Niepoprawne hasło");
}
}
return View(model);
}
Startup.cs
services.Configure<IdentityOptions>(options =>
{
options.Password.RequireDigit = true;
options.Password.RequireLowercase = true;
options.Password.RequireUppercase = true;
options.Password.RequireNonAlphanumeric = true;
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
options.Lockout.MaxFailedAccessAttempts = 5;
//options.Lockout.AllowedForNewUsers = true;
options.SignIn.RequireConfirmedEmail = false;
options.SignIn.RequireConfirmedAccount = false;
options.SignIn.RequireConfirmedPhoneNumber = false;
});
答案
默认情况下,执行NormalizedUserName
时,asp.net核心身份将使用SignInManager.PasswordSignInAsync
登录。如果要使用Identifier
登录,一种简单的方法是直接将NormalizedUserName
用作标识符:
NormalizedUserName = "00001",
以上是关于无法从PasswordHasher登录种子的自定义IdentityUser的主要内容,如果未能解决你的问题,请参考以下文章
与 MethodChannel 一起使用的自定义 Facebook 登录