Search code examples
c#asp.net-mvcasp.net-identityasp.net-identity-2

Invalid login attempt. when login identity asp mvc


I using this code for check login :

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{

    if (!ModelState.IsValid)
    {
        return View(model);
    }
    var user = await UserManager.FindByEmailAsync(model.Email);
    if (user != null)
    {
        if (!await UserManager.IsEmailConfirmedAsync(user.Id))
        {
            ViewBag.errorMessage = "You must have a confirmed email to log on.";
            return View("Error");
        }
    }
    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);
    }
}

when I login show me this error : Invalid login attempt. but Email and password has exist .

This code :

var user = await UserManager.FindByEmailAsync(model.Email);

Not null but this code is Failure :

 var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);

whats the problem ? How solve this problem ?


Solution

  • If you have already found a valid user via email then use the username of the found user to sign in.

    //...
    var user = await UserManager.FindByEmailAsync(model.Email);
    if (user != null) {
        if (!await UserManager.IsEmailConfirmedAsync(user.Id)) {
            ViewBag.errorMessage = "You must have a confirmed email to log on.";
            return View("Error");
        }
    }
    var result = await SignInManager.PasswordSignInAsync(user.Username, model.Password, model.RememberMe, shouldLockout: false);
    //...