1
votes

I'm trying to authenticate users against Active Directory and I'm using the code below to validate their credentials.

bool isValid = principalContext.ValidateCredentials(username, password, ContextOptions.Negotiate);

if (isValid)
{
    userPrincipal = UserPrincipal.FindByIdentity(principalContext, username);
}

My problem is that the ValidateCredentials method doesn't validate the user's password when username = "domain\username" and always returns true, but when the username = "username" or [email protected], it works and return false when the password is invalid.

Scenario 1:

username = "CorrectUserName" and password = "IncorrectPassword" => isValid = false.

username = "CorrectUserName" and password = "CorrectPassword" => isValid = true.

Scenario 2:

username = "[email protected]" and password = "IncorrectPassword" => isValid = false.

username = "[email protected]" and password = "CorrectPassword" => isValid = true.

Scenario 3 (this is my problem):

username = "Domain\CorrectUserName" and password = "IncorrectPassword" => isValid = true.

username = "Domain\CorrectUserName" and password = "CorrectPassword" => isValid = true.

My code looks like this tutorial with minor changes.

I don't know what I'm doing wrong here.

1
When you initialize the PrincipalContext, you should be defining the domain. When you pass the username to the validate method, it does not want a domain pre- or app-ended.Maximilian Burszley
I can't replicate your problem. Specifying username prefixed with domain as in your Scenario 3, I get false for correct and incorrect passwords as I'd expect.itsme86
@itsme86 i tried to replicate my problem with two of my co-workers and it returns true for incorrect passwords. but in ValidateCredentials docs in remaks section that the userName argument must take the form username (for example, mcampbell) rather than domain\username or username@domain.tariku

1 Answers

2
votes

ValidateCredentials takes a username without domain information. The domain should be defined when creating the PrincipalContext:

if (!username.Contains("@") && !username.Contains(@"\"))
{
    // EXCEPTION
}

var domain = username.Contains("@") ? username.Split("@")[1].Split(".")[0] : username.Split(@"\")[0];
var principalContext = new PrincipalContext(ContextType.Domain, domain);

var user = username.Contains("@") ? username.Split("@")[0] : username.Split(@"\")[1];
var isValid = principalContext.ValidateCredentials(user, cleartextpw);

PrincipalContext

ValidateCredentials