Search code examples
asp.netasp.net-mvcasp.net-identity

MVC UserManager Login Case Insensitive Username


I'm trying to fix a bug in my application at the moment where the user email used for login is case sensitive when it should be case insensitive.

I am using the following code to do this in MVC:

public ActionResult Login(LoginViewModel model, string returnUrl)
{
    if (ModelState.IsValid)
    {
        var user = _userManager.Find(model.UserName, model.Password);

        if (user != null)
        {
            SignIn(user, model.RememberMe);
            return RedirectToAction("List", "Survey");
        }

        ModelState.AddModelError("LoginFailure", "Invalid username or password.");
    }

    return View(model);
}

_userManager is a UserManager, an override of the standard AspNet Identity UserManager. It seems as though this is using case sensitive comparisons.

I have looked into a number of ways of fixing this problem, including the obvious one of lower- or upper-casing all of the usernames as they are entered and changing the database to match, but I would rather fix this problem without having to edit the database if possible. I have already tried using lambda expressions but these do not seem to work for the Find method unfortunately.

My username column in the database has its collation as SQL_Latin1_General_CP1_CI_AS which I believe makes it case-insensitive for comparisons.

I have looked around for some time now and cannot find anybody complaining of exactly the same problem apart from the person in this link.

I would be very grateful for any help with this problem that does not involve DB manipulations, or even confirmation if that is the only way possible. Thank you.


Solution

  • Thanks to Sam Farajpour Ghamari's comments, I was able to find the override for the UserStore's findUserByName method and change this code:

    public User GetByUsername(string username)
    {
        return GetAll().FirstOrDefault(u => u.UserName == username);
    }
    

    to this:

    public User GetByUsername(string username)
    {
        return GetAll().FirstOrDefault(u => u.UserName.ToLower() == username.ToLower());
    }
    

    And it worked. Thanks for the help.