简体   繁体   中英

How to properly authenticate user against Active Directory?

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 username@domain.com , 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 = "CorrectUserName@Domain.com" and password = "IncorrectPassword" => isValid = false.

username = "CorrectUserName@Domain.com" 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM