Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.Net Identity - case insensitive email and usernames

Is there a way to get Asp.Net Identity to be case insensitive with email addresses and usernames?

At the moment if I call "FindByEmailAsync(email)" it will only work if the email address is being stored exactly as it's is typed (case sensitive)

like image 316
user441365 Avatar asked Jul 15 '14 15:07

user441365


1 Answers

You can change how the user is registered so that the username is set to lowercase and when logging in as well.

For registering the user, in the AccountController

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(RegisterViewModel model)
    {
        if (ModelState.IsValid)
        {
            var user = new ApplicationUser() { UserName = model.Email.ToLowerInvariant(), Email = model.Email };
            IdentityResult result = await UserManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                await SignInAsync(user, isPersistent: false);

                return RedirectToAction("Index", "Home");
            }
            else
            {
                AddErrors(result);
            }
        }

And for logging in:

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
    {
        if (ModelState.IsValid)
        {
            var user = await UserManager.FindAsync(model.Email.ToLowerInvariant(), model.Password);
            if (user != null)
            {
                await SignInAsync(user, model.RememberMe);
                return RedirectToLocal(returnUrl);
            }
            else
            {
                ModelState.AddModelError("", "Invalid username or password.");
            }
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }
like image 120
Rui Avatar answered Sep 28 '22 04:09

Rui