Miguel Moura
Miguel Moura

Reputation: 39484

Create user without UserManager in Asp.Net Core Identity

On an ASP.NET Core 1.1 application with ASP.NET Identity I created a user:

PasswordHasher<User> hasher = new PasswordHasher<User>();

User user = new User {
  Email = "[email protected]",
  Username = "[email protected]
};

user.PasswordHash = hasher.HashPassword(user, "johnpass");

context.Users.Add(user);
context.SaveChanges();

The user is created but when I try to sign using the following it fails:

SignInResult result = await _signInManager.PasswordSignInAsync("[email protected]", "johnpass", false, true);     

I then tried to create the user using the UserManager:

PasswordHasher<User> hasher = new PasswordHasher<User>();

User user = new User {
  Email = "[email protected]",
  Username = "[email protected]
};

await userManager.CreateAsync(user, "johnpass");

Now I am able to sign in. It seems the problem is with HashPassword method.

Does anyone knows how to create the user without UserManager?

UPDATE
I tried to create a UserManager without reeling on Injection because I am creating my test data on a Console Application and not on the Web Application:

var userStore = new UserStore(Context);

var userManager = new UserManager<User>(userStore, null, null, null, null, null, null, null, null); 

The user is created but I am still not able to sign in.

Upvotes: 2

Views: 5943

Answers (2)

Przemysław R
Przemysław R

Reputation: 107

you have to do the following things:

userManager.UpdateSecurityStampAsync(domainUser);
        domainUser.NormalizedUserName = domainUser.NormalizedEmail = domainUser.UserName = domainUser.Email;
        await userManager.UpdateNormalizedUserNameAsync(domainUser);
        await userManager.UpdateNormalizedEmailAsync(domainUser);
        await userManager.UpdateAsync(domainUser);

and if you set up in your config email confirmation

var token = await userManager.GenerateEmailConfirmationTokenAsync(domainUser);
await userManager.ConfirmEmailAsync(domainUser, token);

Upvotes: 3

Eng. Ahmed Othman
Eng. Ahmed Othman

Reputation: 1

Follow the following scenario in login.

  1. get the user using userName or Email.
    user = context.Users.FirstOrDefault(usr => usr.UserName == userName);

  2. Check if this user has this password or not using: userManager.CheckPasswordAsync(user, password);

where userManager is an object from UserManager<User>

Upvotes: 0

Related Questions