2

I have a simple DbContext with a Set<> of users.

I've got an ASP.NET Core Web API with authentication.

public User Authenticate(string username, string password)
{
    var user = _ctx.Users.FirstOrDefault(x => 
            x.Username.Equals(username, StringComparison.OrdinalIgnoreCase) && 
            x.Password.Equals(password, StringComparison.OrdinalIgnoreCase));

    bool exists = _ctx.Users.Any(x =>
            x.Username.Equals(username, StringComparison.OrdinalIgnoreCase) &&
            x.Password.Equals(password, StringComparison.OrdinalIgnoreCase));

    bool usernameCorrect = _ctx.Users.First().Username.Equals(username, StringComparison.OrdinalIgnoreCase);
    bool passwordCorrect = _ctx.Users.First().Password.Equals(password, StringComparison.OrdinalIgnoreCase);

    if (user == null)
    {
        return null;
    }
    [...]
}

The problem is that _ctx.Users.FirstOrDefaultis returning null.

You might think this is simple: "the condition does not match"

But:

What is going on here?

0

1 Answer 1

1

What's happening is that the comparison with OrdinalIgnoreCase works only with materialized object. (Your IQueryable provider does not support it). It is working in the 3rd and 4th case because you materialized the object first.

try instead using string.Compare(string str1, string str2, StringComparison.OrdinalIgnoreCase) == 0

Sign up to request clarification or add additional context in comments.

4 Comments

This does not work ;( I get an exception by entityframework sayin it cannot be translated.
But I get the point. _ctx.Users.SingleOrDefault(x => x.Username.Equals(username) && x.Password.ToLower().Equals(password.ToLower())); is working fine!
StringComparison.OrdinalIgnoreCase is usually a bad practice for comparing usernames and passwords, but if you really want it so you can convert your strings to lower case and use the normal == to compare your strings as a workaround
I'm working with md5 hashes right now. I guess it's fine to lower them :P

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.