Search code examples
c#asp.net-coreasp.net-core-identity

ASP.NET Core Identity - Creating user "manually" and providing password hash - How to generate hash correctly?


I must create user manually:

var user = new User
{
    Name = "Joe",
    Email = "test@****.com",
    PasswordHash = "gdfgdfgre2132143xcxzvb=="
}

context.Users.Add(user);

but the thing is that when I try to log into that account my password doesn't work.

I copied Password's hash of User account that I know password to and then I pasted it to that new User and tried to use the same password and it didnt work - password sign in failed

So I'd want to ask - what's wrong with my logic here and how can I make it work?

Is it related to SecurityStamp?


Solution

  • If you want to manually add the user , you should also set the NormalizedUserName property . In addition , it's better to use IPasswordHasher<TUser> Interface for hashing passwords:

    The injected services :

    private readonly ApplicationDbContext _context;
    public readonly IPasswordHasher<IdentityUser> _passwordHasher;
    
    public HomeController( ApplicationDbContext dbContext, IPasswordHasher<IdentityUser> _passwordHasher)
    {
    
        this._context = dbContext;
        this._passwordHasher = _passwordHasher;
    
    }
    

    I assume your User inherits IdentityUser , here i use IdentityUser for example:

    IdentityUser applicationUser = new IdentityUser();
    Guid guid = Guid.NewGuid();
    applicationUser.Id = guid.ToString();
    applicationUser.UserName = "Joe";
    applicationUser.Email = "[email protected]";
    applicationUser.NormalizedUserName = "[email protected]";
    
    _context.Users.Add(applicationUser);
    
    
    var hashedPassword = _passwordHasher.HashPassword(applicationUser, "YourPassword");
    applicationUser.SecurityStamp = Guid.NewGuid().ToString();
    applicationUser.PasswordHash = hashedPassword;
    
    _context.SaveChanges();
    

    You can also use UserManager.CreateAsync to create the specified user in the backing store with given password :

    var user = new IdentityUser { UserName = "Joe", Email = "[email protected]" };
    var result = await _userManager.CreateAsync(user, "YourPassWord");
    if (result.Succeeded)
    {
    
    }
    

    Notice : You should provide Email value during login .