首先,我查看了关于 SO 的大多数问题,但似乎都不是完全相同的问题。 Here是一个类似的问题,但并不完全相同。在我的情况下,我正在创建一个 PrincipalContext :
Dim pctx As PrincipalContext = New PrincipalContext(ContextType.Domain, fullyqualifieddomain, container, ADUserID, ADPassword)
If pctx.ValidateCredentials(userName, password) Then
ADUserID 是一个服务帐户。
此方法有效,但需要 6-10 秒以上。
我也尝试过直接检索底层目录条目和绑定(bind)。这要快得多,并且可以在我的机器(域外)上工作,但不能在 Web 服务器(域内)上工作。它在 DirectoryEntry.NativeObject 调用时失败。我不知道为什么。不幸的是,我处于这样一种情况,即唯一可行的方法太慢而无法实现。有没有办法加快这个速度?
提前致谢!
最佳答案
试试下面的代码。它可能不会更快,但很高兴看看它是否有效。
用户名应该不包括域。对于域,我的测试只使用了短名称“DOMAIN”,而不是 DN 甚至完全限定(您的里程可能会有所不同)。
添加对 System.DirectoryServices.Protocols 的引用。
using System.DirectoryServices.Protocols;
public static bool Authenticate(string username, string password, string domain)
{
try
{
//string userdn;
using (LdapConnection lconn = new LdapConnection(new LdapDirectoryIdentifier(domain)))
{
lconn.Bind(new System.Net.NetworkCredential(username, password, domain));
return true;
}
}
catch (LdapException e)
{
return false;
}
}
if (Authenticate("username", "password", "domain")) { }
关于.net - PrincipalContext.ValidateCredentials 非常慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10920567/