Search code examples
.netasp.net-coreentity-framework-coreasp.net-core-identitypassword-hash

Cannot login to seeded custom IdentityUser from PasswordHasher


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;
});

Solution

  • 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",