返回'true'的方法应该返回'false'

我正在使用Active Directory DirectoryServices.AccountManagement API,并尝试使用以下代码连接到服务器:

 PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, (server + ":" + port), loginUsername, loginPassword); 

我想要做的第一件事是检查loginUsernameloginPassword是否有效并且在Active Directory实例中具有足够的权限。 为了达到这个目的,我呼吁:

 bool x = principalContext.ValidateCredentials(null, null); 

根据文档 ,这将validation自传递null以来在构造函数中指定的凭据。 在debugging器中,会引发以下错误,指示凭据为false:

在这里输入图像说明

但是,ValidateCredentials检查的实际结果奇怪地返回true ,代码继续执行。

这怎么解决?

编辑:

这里是另一个截图详细说明了错误。 如截图所示,我调用ValidateCredentials方法,并为用户名和密码传递null值,根据文档将尝试validation在PrincipalContext类的构造函数中传递的凭据。

该屏幕截图还显示了传递的用户名和密码如何都是“testing”,这些都是无效的,并且不存在于Active Directory中。 该方法返回true,即使显示了一些错误。

在这里输入图像说明

你只需要停止查找空值…

 if (string.IsNullOrEmpty(password) || string.IsNullOrEmpty(username)) return false; 

我跑了一些测试

  using (var pc = new PrincipalContext(ContextType.Domain, "mydomain.lan")){ var isOk1 = pc.ValidateCredentials(null,null); //Always true var isOk2 = pc.ValidateCredentials("notexists","wrong"); //false var isOk2 = pc.ValidateCredentials("existing","correct"); //true } 

  using (var pc = new PrincipalContext(ContextType.Domain, "mydomain.lan", "notright","wrong")){ var isOk1 = pc.ValidateCredentials(null,null); //Always true var isOk2 = pc.ValidateCredentials("notexists","wrong"); //false var isOk2 = pc.ValidateCredentials("existing","correct"); //true } 

所以ValidateCredentials在上下文中确实不需要用户…如果你提供一个错误的用户,那么下面的用户组查找就会失败

是的,文档中写道:

ValidateCredentials方法绑定到构造函数中指定的服务器。 如果用户名和密码参数为空,则会验证构造函数中指定的凭据。 如果在构造函数中没有指定凭证,且用户名和密码参数为空,则此方法验证当前主体的默认凭证。
http://msdn.microsoft.com/en-us/library/bb154889%28v=vs.100%29.aspx

但我无法证实,构造函数中的信用在起作用

编辑:你已经接受了,但也许你可以使用这个方法来解决你的问题?

  using (var pc = new PrincipalContext(ContextType.Domain, "domain.lan", username, password)) { if (pc.ValidateCredentials(username, password)) { try { using (var searcher = new PrincipalSearcher(new UserPrincipal(pc))) { searcher.QueryFilter.SamAccountName = username; Principal u = searcher.FindOne(); } } catch (Exception) { return "no rights to work on ad"; } } else { return "user cannot login"; } }