简体   繁体   中英

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?

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
            }
        }
    }

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