I am currently implementing the ability to login on my ASP.NET MVC project. I am trying to use as much of the provided methods as I can.
Currently, I have set up a table in my database known as User, which stores all the usernames, passwords and other details regarding the users.
My LoginViewModel:
public class LoginViewModel
{
public User User { get; set; }
}
The AccountController (which is mostly the default, I have only changed the variables of the PasswordSignInAsync method)
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (ModelState.IsValid)
{
return View(model);
}
// To enable password failures to trigger account lockout, change to shouldLockout: true
var result = await SignInManager.PasswordSignInAsync(model.User.Username, model.User.Password, false , shouldLockout: false);
Why does this line always return a Failure?
It's my first time trying to add the Login ability, so any help would be greatly appreciated. :)
If username != email:
comment out:
//var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
and add
ApplicationUser signedUser = UserManager.FindByEmail(model.Email);
var result = await SignInManager.PasswordSignInAsync(signedUser.UserName, model.Password, model.RememberMe, shouldLockout: false);
Retrieve User
based on model.Email
and pass the entire User object as first parameter.
var user = dbContext.ApplicationUser.GetFirstOrDefault(u => u.Email == model.Email);
The above query returns the userdata. Check if the user is null. Verify retrieved userdata and pass it as a parameter to PasswordSignInAsync
. There are two different methods differed with parameter types.
PasswordSignInAsync(String, String, Boolean, Boolean)
Attempts to sign in the specified userName and password combination as an asynchronous operation.
PasswordSignInAsync(TUser, String, Boolean, Boolean)
Attempts to sign in the specified user and password combination as an asynchronous operation.
PasswordSignInAsync(TUser, String, Boolean, Boolean)
performs similar operations as the above and succeeds the result. Below is the query to retrieve success result.
var result = await _signInManager.PasswordSignInAsync(user, model.Password, model.RememberMe, lockoutOnFailure: false);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With