Search code examples
c#active-directoryprincipalcontext

PrincipalContext.ValidateCredentials: find username or password is invalid


I am using AD authentication in my application:

 bool _isValid;
 using (var pc = new PrincipalContext(ContextType.Domain, DomainPath))
 {
     isValid = pc.ValidateCredentials(username, password, ContextOptions.Negotiate);
 }

Is there any way to find out if I am getting isValid set to false because of an invalid username or an invalid password?


Solution

  • You can't be sure directly which one is invalid. But you can try to retrieve the user from active directory to determine which one is wrong after false validation like this;

        bool _isValid;
        using (var pc = new PrincipalContext(ContextType.Domain, DomainPath))
        {
            isValid = pc.ValidateCredentials(username, password, ContextOptions.Negotiate);
            if (!isValid)
            {
                var user = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, username);
                if (user == null)
                {
                    //User doesn't exist
                }
                else
                {
                    //Password is invalid
                }
            }
        }