Chris Chris - 3 years ago 128
C# Question

Creating users outside of using the AccountController and passwords are failing when trying to login

I am creating users without using the AccountController, and after the user is successfully created, I go and try to log in with that users email and password and it keeps failing all the time, and I have no idea why it would fail because I am creating the users with the same passwords.

Is there something that I could be doing wrong while creating a user without using the AccountController? and I am also adding the new users to the AspNetUser table

The code is

AspNetUser user = new AspNetUser();

user.UserName = ahl.AccountHolderName;
user.SecurityStamp = Guid.NewGuid().ToString();
user.PasswordHash = pHasher.HashPassword(ahl.AccountHolderPassword);
user.Email = ahl.AccountHolderEmail;
user.Id = Guid.NewGuid().ToString();

HWC.AspNetUsers.Add(user);
HWC.SaveChanges();


incase anyone asks why I just don't use the AccountController is because I don't want to always have to rely on that controller.

EDIT

Here is the login code that is being called when logging in

public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (!ModelState.IsValid)
{
return View(model);
}

// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, change to shouldLockout: true
var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
switch (result)
{
case SignInStatus.Success:
return RedirectToLocal(returnUrl);
case SignInStatus.LockedOut:
return View("Lockout");
case SignInStatus.RequiresVerification:
return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
case SignInStatus.Failure:
default:
ModelState.AddModelError("", "Invalid login attempt.");
return View(model);
}
}

DSR DSR
Answer Source

The issue is you have been using two different values for UserName and Email for newly created user.

SignInManager.PasswordSignInAsync() check `userName` and `Password`, not `Email` and `Password` which you are passing in your code. 

Change user.UserName = ahl.AccountHolderName; code to user.UserName = ahl.AccountHolderEmail; when creating user, then this should work.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download