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

问题描述 投票:0回答:2

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

我有服务器 IP、域名、用户名/密码和端口 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;
    }            

背景信息: 用户将其卡放入读卡器单元。 Porgram 从卡中获取 ID,并在数据库中搜索该 ID,然后返回属于该 ID/用户的电子邮件地址 。 这是工作解决方案:

        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);
    }
c# active-directory ldap
2个回答
10
投票

您需要指定端口,因为 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 证书存储中的机构颁发的。


0
投票

我想使用 LDAPS://domain:636 来查询,但失败了...... 但是当我尝试使用 LDAP://domain:636 进行相同操作时,它可以工作 需要哪些其他配置才能使 LDAPS:// 工作

© www.soinside.com 2019 - 2024. All rights reserved.