PrincipalContext.ValidateCredentials: 发现用户名或密码无效

PrincipalContext.ValidateCredentials: find username or password is invalid

我在我的应用程序中使用 AD 身份验证:

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

有什么方法可以查明我是否因为用户名或密码无效而将 isValid 设置为 false

你不能直接确定哪个无效。但是你可以尝试从活动目录中检索用户,以确定在这样的错误验证后哪个是错误的;

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