我有一個VMWare
機器Windows Server 2012
和Active Directory
安裝。域名是「cpx.local
」,我創建了一個新用戶「testad
」。c#LDAP認證奇怪的問題
我有一個C#
WinForm應用程序,所以我可以測試到LDAP
服務器的連接,然後獲得在Active Directory
所有用戶或組。
這是正常工作的代碼:
string server = "192.168.238.129";
string port = "389";
System.DirectoryServices.Protocols.LdapConnection ldapConnection =
new System.DirectoryServices.Protocols.LdapConnection(new LdapDirectoryIdentifier(server + ":" + port));
TimeSpan mytimeout = new TimeSpan(0, 0, 0, 1);
try
{
ldapConnection.AuthType = AuthType.Anonymous;
ldapConnection.AutoBind = false;
ldapConnection.Timeout = mytimeout;
ldapConnection.Bind();
Console.WriteLine(("Successfully authenticated to ldap server "));
ldapConnection.Dispose();
}
catch (LdapException ex)
{
Console.WriteLine(("Error with ldap server "));
Console.WriteLine((ex.GetType().ToString() + (":" + ex.Message)));
}
的問題是,如果我想和新用戶「testad
」來驗證它不工作。
我將AuthType更改爲Basic並設置憑據。
ldapConnection.AuthType = AuthType.Basic;
ldapConnection.Credential = new NetworkCredential(@"cpx\testad", "[email protected]", "cpx.local");
ldapConnection.AutoBind = false;
ldapConnection.Timeout = mytimeout;
ldapConnection.Bind();
我得到以下錯誤:
我曾嘗試與該用戶登錄時,Windows Server 2012中,我可以登錄完美。
有趣的是,下面的代碼工作正常:
var dirEntry = new DirectoryEntry(string.Format("LDAP://{0}/{1}", "192.168.238.129:389", "DC=cpx,DC=local"), "testad", "[email protected]");
var searcher = new DirectorySearcher(dirEntry)
{
Filter = "(&(&(objectClass=user)(objectClass=person)))"
};
var resultCollection = searcher.FindAll();
I don't know if what Im doing something wrong with the NetworkCredentials. Any advice is well appreciated.
您是否嘗試過這裏給出的建議? https://stackoverflow.com/questions/11561689/using-c-sharp-to-authenticate-user-against-ldap和在這裏? https://support.microsoft。com/en-us/help/316748/how-to-authenticate-against-active-directory-by-using-forms-authen –
另外,在'using'語句中使用'ldapConnection'變量來確保對象在拋出異常的情況下處理。 –