ValidateCredentials conditions to return false

658 Views Asked by At

I'm using PrincipalContext's ValidateCredentials method to authenticate into Active Directory, but for some reason it returns false despite the password being correct and not expired. I've checked for the state of the user with UserPrincipal, but despite the user being enabled and not locked, it still returns false. I also made sure that the last password set wasn't past its expiration date.

Are there other factors that make ValidateCredentials return false?

Code used:

bool expired = false;
bool blocked = false;
bool disabled = false;
int failedLogins;

Resultado resul = new Resultado();
PrincipalContext domainContext = new PrincipalContext(ContextType.Domain, Config.ActiveDirectory.Server,
                                                                            Directory,
                                                                            Config.ActiveDirectory.User,
                                                                            Config.ActiveDirectory.Pass);
UserPrincipal user = UserPrincipal.FindByIdentity(domainContext, userName);

if (user != null)
{
    disabled = (user.Enabled == null || !user.Enabled.Value);
    blocked = user.IsAccountLockedOut();
    expired = user.LastPasswordSet == null || DateTime.UtcNow.Subtract(user.LastPasswordSet.Value).Days >= Config.ActiveDirectory.MaxPassAge;

    failedLogins = user.BadLogonCount; 


    if (domainContext.ValidateCredentials(userName, password))
        resul.ResultCode = 0;
    else
    {
        user = UserPrincipal.FindByIdentity(domainContext, userName);

        if (disabled)
            resul.ResultCode = 7;
        else if (blocked)
            resul.ResultCode = 3;
        else if (failedLogins != user.BadLogonCount)
            resul.ResultCode = 2;
        else
            resul.ResultCode = 4;
    }
}
else
    resul.ResultCode = 1;
return resul;
1

There are 1 best solutions below

4
Gabriel Luci On

You can also check the account expiration date using the AccountExpirationDate property.

Also, check if the password must be changed on next logon. The LastPasswordSet property will be null if that's the case.

There is also a note in the documentation for ValidateCredentials that might be relevant:

The userName argument must take the form username (for example, mcampbell) rather than domain\username or username@domain.

Have you tried logging into a computer with that username and password? That is the best way to determine if ValidateCredentials is lying to you or not.

Curious: why are you setting user to the same thing again in your else block? That seems unnecessary.