Search code examples
asp.net-mvc-5asp.net-identity-2

Login with Email in MVC 5


In newly created ASP.NET MVC5 application, the login screen asks you to enter Email address. But under the hood, it authenticates with user name assuming applicationUser.UserName == applicationUser.Email.

How to change it to make it authenticate user via Email address?

It seems like they have changed something in Identity 2.x in that regard.

Note: I want to keep it login via Email.

For example, in register view, our users are expected to provide:

Email: last.first@example.com

User: Last, First

And during Login, the email will be used. Currently, it uses email but authentication fails because it passes email as user-name.


Solution

  • In Login#Accounts:

    After

    if (!ModelState.IsValid) 
    { 
        return View(model); 
    } 
    

    I added:

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

    And changed:

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

    to:

    var result = user == null ? SignInStatus.Failure : await SignInManager.PasswordSignInAsync(user.UserName, model.Password, model.RememberMe, shouldLockout: false); 
    

    In register view, I have User Name as well as Email (for which I had to add UserName property in RegisterViewModel).