André Luiz
André Luiz

Reputation: 7302

Asp.NET MVC 5 validate user by e-mail and password

I'm using a Asp.NET MVC 5 project that came with a Bootstrap 3 theme we bought and in its login method they just look for the user based on his e-mail, the password is not validated. Login method below:

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Login(AccountLoginModel viewModel)
    {
        // Ensure we have a valid viewModel to work with
        if (!ModelState.IsValid)
            return View(viewModel);

        // Verify if a user exists with the provided identity information
        var user = await _manager.FindByEmailAsync(viewModel.Email);
        var hashPass = new PasswordHasher().HashPassword(viewModel.Password); // this is a line I added which gerenates a different hash everytime
        // If a user was found
        if (user != null)
        {
            // Then create an identity for it and sign it in
            await SignInAsync(user, viewModel.RememberMe);

            // If the user came from a specific page, redirect back to it
            return RedirectToLocal(viewModel.ReturnUrl);
        }

        // No existing user was found that matched the given criteria
        ModelState.AddModelError("", "Invalid username or password.");

        // If we got this far, something failed, redisplay form
        return View(viewModel);
    }

The line I'm trying to insert the password validation is the if (user != null). I tried using _manager.Find(email,password) but it doesn't work.

How can I login the user with his e-mail and validate the password?

Upvotes: 1

Views: 818

Answers (2)

manika
manika

Reputation: 187

-------Try this code------

var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
        switch (result)
        {
         case SignInStatus.Success:
            return View("SuccessView");             
         case SignInStatus.Failure:
            return View("LoginView");
        }

Upvotes: 0

Nkosi
Nkosi

Reputation: 247333

That is because you are hashing the password before trying to find the user.

Do

var user = _manager.Find(viewModel.Email, viewModel.Password);
// If a user was found
if (user != null)
{
    //...other code removed for brevity.

which is the standard way to do it.

Upvotes: 1

Related Questions