PrincipalContext.ValidateCredentials:查找用户名或密码无效

时间:2017-11-23 05:22:22

标签: c# active-directory principalcontext

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

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

有没有办法查明我是否因为用户名无效或密码无效而将isValid设置为false

1 个答案:

答案 0 :(得分:0)

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

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