Cannot login to seeded custom IdentityUser from PasswordHasher

.net asp.net-core asp.net-core-identity entity-framework-core password-hash

Question

I created user in context OnModelCreating method. When I m trying to login using given password it always fails.

I also tried to create new account by using UserManager and it works like a charm.

I think the problem is somewhere in PasswordHasher.

Context class

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;
});
1
0
2/18/2020 7:24:45 PM

Accepted Answer

By default , asp.net core identity will login using NormalizedUserName when performing SignInManager.PasswordSignInAsync . If you want to use Identifier to login , a simply way is to use NormalizedUserName directly as Identifier :

NormalizedUserName = "00001",
0
2/19/2020 6:21:25 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow