Dot-Net

PrincipalContext.ValidateCredentials 非常慢

  • April 3, 2018

首先,我查看了關於 SO 的大多數問題,但似乎都不是完全相同的問題。是一個類似的問題,但並不完全相同。在我的情況下,我正在創建一個 PrincipalContext :

Dim pctx As PrincipalContext = New PrincipalContext(ContextType.Domain, fullyqualifieddomain, container, ADUserID, ADPassword)


  If pctx.ValidateCredentials(userName, password) Then

ADUserID 是一個服務帳戶。

此方法有效,但需要 6-10 秒以上。

我也嘗試過直接檢索底層目錄條目和綁定。這要快得多,並且可以在我的機器(域外)上工作,但不能在 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")) { }

引用自:https://stackoverflow.com/questions/10920567