11

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?

0

1 Answer 1

16

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 .

Sign up to request clarification or add additional context in comments.

4 Comments

the thing is, that I'm creating this account in tests and injecting all those REAL Identity related classes is painful for me
Then you can use the manually way , provider related properties .
Thanks! Apparently creating an instance of PasswordHasher didnt require any other dependencies - everything works fine!
The default "POST /login" endpoint of app.MapIdentityApi<User>() returns status code 401 "Unauthorized" until I do a ToUpperInvariant() on the email before setting it for NormalizedUserName. This matches the behavior of the "POST /register" endpoint.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.