如何在 C# 中通过 LDAPS 连接到 Active Directory?

How to connect to Active Directory via LDAPS in C#?

在此站点的回答线程中找到文档 (here),但我无法连接到 AD。当我使用像 Active Directory Explorer 这样的程序时,我可以连接。我想,因为我正在尝试连接到 LDAPS,所以我需要一种不同的方法?

我有服务器 IP、域、username/pwd 和端口 636。 我尝试了各种组合 @ new DirectoryEntry 但无法连接。总是得到一个 COMException Domain is not existing .

    static DirectoryEntry createDirectoryEntry()
    {
        DirectoryEntry ldapConnection = new DirectoryEntry("LDAP://192.168.2.59", USER, PWD);

        ldapConnection.AuthenticationType = AuthenticationTypes.SecureSocketsLayer;

        return ldapConnection;
    }            

背景信息: 用户将他的卡片放在卡片 Reader 单元中。 Porgram 从卡中获取 ID 并在数据库中搜索此 ID 和 returns 属于 ID/User 的电子邮件地址 . 这里是工作解决方案:

        private string getEmail(string userID)
    {
        try
        {
            string ldapfilter = "(&(otherPager=" + userID + "))";

            DirectoryEntry myLdapConnection = new DirectoryEntry("LDAP://" + SERVER, USER, PWD);
            DirectorySearcher search = new DirectorySearcher(myLdapConnection);
            search.Filter = ldapfilter;

            /*search.PropertiesToLoad.Add("mail");
            SearchResult result = search.FindOne();*/

            string[] requiredValue = new String[] { "mail" };

            foreach (String value in requiredValue)
                search.PropertiesToLoad.Add(value);

            SearchResult result = search.FindOne();

            if (result != null)
            {
                foreach (String value in requiredValue)
                    foreach (Object myCollection in result.Properties[value])
                    {
                       return myCollection.ToString();
                    }    
            }
            else
            {
                return "No Entry fround";
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("Exception Problem: " + e.ToString());
            return null;
        }
        return null;
    }



    private void cmdClose_Click(object sender, EventArgs e)
    {
        Close();
    }

    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        label1.Text = getEmail(textBox1.Text);
    }

您需要指定端口,因为 636 是默认的 LDAPS 端口。

new DirectoryEntry("LDAP://192.168.2.59:636", USER, PWD)

我在我的一些代码中这样做,使用 "LDAP://"(而不是 "LDAPS://")是可行的。

如果这不起作用,则可能是证书错误。您可以使用浏览器对此进行测试。如果你使用 Chrome,用这个打开 Chrome(所以它允许你使用端口 636):

"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --explicitly-allowed-ports=636

然后前往https://192.168.2.59:636。如果你得到一个很大的证书错误,那么问题是证书不受信任。从 Chrome 查看证书,看看问题是什么。它可能由不在 Windows 证书库中的机构颁发。