Search code examples
c#asp.netasp.net-mvcasp.net-mvc-5asp.net-identity-2

ASP.NET Identity 2 Separation of Email and UserName and using Email to login


By default, ASP.NET Identity has the UserName and Email fields as being the email the user inputs. I've already changed it so that my system takes in a separate username and email for the user.

My problem is that now I cannot login to the system because of the checks Identity does against both the UserName and Email.

I was wondering if there was a way to keep these two fields separate and unique, while being able to just check against the Email field in order to login to the system?

I noticed that public virtual Task<SignInStatus> PasswordSignInAsync(string userName, string password, bool isPersistent, bool shouldLockout); checks the userName, but changing this to the email does nothing and I am still unable to login.

I've also looked at these other questions:

ASP.Net UserName to Email

Allowing both email and username for authentication

for possible solutions and found nothing really allowed me to do what I want.

Is there anything else I could possibly attempt in order to have separate usernames and emails, while still being able to login with the email field?


Solution

  • So, it looks like you can only authenticate using a username, but there's no reason why you can't find the user name from an email address:

    var user = await UserManager.FindByEmailAsync(model.Email);
    if (user == null)
    {
    
        return //some error or throw
    }
    var result = await 
        SignInManager.PasswordSignInAsync(user.UserName, 
                                          model.Password, 
                                          model.RememberMe, 
                                          shouldLockout: false);