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

Identity 2.0 Invalid Login Attempt


For some reason I am yet to discover, but after a successful registration and activation, I cannot login with the email address, instead I get an error "Invalid login attempt".

As ASP.NET Identity 2.0 has improved with the use of Email login, I have modified the registration form to actually store a true username as the existing registration just seemed to duplicate by storing Username with the email address.

Please see below the standard code that comes with Install-Package Microsoft.AspNet.Identity.Samples -Pre' following the creation of an empty ASP.NET Web Application (MVC) project:

var user = new ApplicationUser { UserName = model.Email, Email = model.Email };

My function is now as follows:

var user = new ApplicationUser { TitleId = model.TitleId, SexId = model.SexId, Forename = model.Forename, Surname = model.Surname, UserName = model.UserName, Email = model.Email, JoinDate = System.DateTime.Now };

As you can see UserName is now receiving a value from a form. This is all well and good except now I can't logon after registration and activation. The only work round is to modify the record by putting the value from the Email field into the UserName field which just seems daft.

Can somebody please advise as to what I might have missed?


Solution

  • You have to modify SignInHelper.PasswordSignIn method. By default it uses FindByNameAsync to check if user with given name exists:

    public async Task<SignInStatus> PasswordSignIn(string userName, string password, bool isPersistent, bool shouldLockout)
    {
        var user = await UserManager.FindByNameAsync(userName);
        // (...)
    

    change it to use FindByEmailAsync:

        var user = await UserManager.FindByEmailAsync(userName);
    

    You can find SignInHelper class in *AppCode\IdentityConfig.cs` file.