Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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: [email protected]

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.

like image 657
Annie Avatar asked Mar 19 '23 07:03

Annie


1 Answers

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

like image 75
Annie Avatar answered Mar 29 '23 08:03

Annie