Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

await SignInManager.PasswordSignInAsync() always results in a failure in my ASP.NET MVC project

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. :)

like image 650
fuzzi Avatar asked Jul 30 '15 22:07

fuzzi


2 Answers

If username != email:

It works for me:

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);
like image 157
Z.W.Huang Avatar answered Oct 06 '22 01:10

Z.W.Huang


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);
like image 36
sarath chandra Avatar answered Oct 06 '22 01:10

sarath chandra