Home > Software engineering >  How to make email case insensitive authentication in ASP.NET Core Web API login
How to make email case insensitive authentication in ASP.NET Core Web API login

Time:10-21

Currently, when a user logs in to my application their email address should be all small letters but that shouldn't be the case, because in most applications whether you capitalize the whole email or the first letter of an email, it should still login.

How can I fix this bug in my application?

I tried changing the database column to be case insensitive but I can't because of the encryption of the data in my database.

My authentication code is like this:

public async Task<User> Login(string? email, string? password)
    {
        if (string.IsNullOrWhiteSpace(password) || string.IsNullOrWhiteSpace(email))
        {
            throw new ClientError("Email and password required.");
        }

        var user = await ValidateUser(email, password);

        return user ?? throw new ClientError("Invalid email or password.");
    }

   
    private async Task<User?> ValidateUser(string email, string password)
    {
        var user = await _queries
            .GetByEmail(email)
            .FirstOrDefaultAsync();

        if (user == null)
        {
            return null; // Email does not exist.
        }

        var passwordIsCorrect = _hashUtil.VerifyHashedPassword(
            email: email,
            password: password,
            hash: user.Password
            );

        if (passwordIsCorrect)
        {
            return user; 
        }

        return null;
    }

CodePudding user response:

Just

var user = await _queries
            .GetByEmail(email.toLower())
            .FirstOrDefaultAsync();

The {string}.toLower() method will convert all chars to lower case hence your database search will always compare lower case emails.

Don't forget to guarantee that when users register you use the same function in the email inputted to assure that the emails saved in database are always lower case as well.

  • Related