【问题标题】:Use SSL to connect to LDAP with .Net DirectoryServices使用 SSL 通过 .Net DirectoryServices 连接到 LDAP
【发布时间】:2019-10-09 21:53:15
【问题描述】:

我有一些 .NET 工作代码(作为桌面应用程序和 IIS 部署)来从 LDAP 读取数据:

string ldapUrl = "LDAP://myLdapUrl.example/ou=user,dc=MyDC";
AuthenticationTypes auth = AuthenticationTypes.None;
using (DirectoryEntry directoryEntry = new DirectoryEntry(
   ldapUrl,
   "cn=ldap_user,ou=user,dc=MyDC",
   "NotMyTruePassword",
   auth)
{
   using (DirectorySearcher directorySearcher = new DirectorySearcher(directoryEntry))
   {
       directorySearcher.PropertiesToLoad.AddRange(new[] { "uid", "givenname", "sn", "middlename", "description", "memberof" });
       directorySearcher.Filter = String.Format("(&(objectclass=person)(cn={0}))", user);
       directorySearcher.SearchScope = SearchScope.OneLevel;
       directorySearcher.SizeLimit = 10;
       SearchResult searchResult = directorySearcher.FindOne();
   }
}

但是当我尝试连接到 LDAPS 端口 (636) 时,它会失败并显示

System.Runtime.InteropServices.COMException (0x8007203A):服务器无法运行。

注意事项:

  • 我已通过 MMC 将服务器 CA 添加到我的帐户中。

  • 之后,我可以使用 LdapAdmin 连接到 LDAPS 端口。

  • 我尝试了以下更改:

    1. 只需将端口添加到服务器 URL1

      string ldapUrl = "LDAP://myLdapUrl.example:636/ou=user,dc=MyDC";
      
    2. 添加端口并将authTypes更改为SecureSocketsLayer2

      string ldapUrl = "LDAP://myLdapUrl.example:636/ou=user,dc=MyDC";
      AuthenticationTypes auth = AuthenticationTypes.SecureSocketsLayer;
      
    3. 添加端口并将authType更改为Secure2

      string ldapUrl = "LDAP://myLdapUrl.example:636/ou=user,dc=MyDC";
      AuthenticationTypes auth = AuthenticationTypes.Secure;
      

而且我总是得到相同的结果。

我找到了一些直接使用 LDAP 连接的示例(来自 System.DirectoryServices.Protocols),但我不想更改代码,因为我已经让它工作了。


1 我经常看到有人声称我应该将LDAP:// 更改为LDAPS:,但似乎DirectoryServices 不是这样工作的。在任何情况下也失败了。

2 我很确定这两个选项是用于身份验证而不是用于设置 SSL 连接,但我还是尝试了它们。

【问题讨论】:

    标签: c# .net ssl ldap directoryservices


    【解决方案1】:

    对于面向安全的连接,我们不能使用 AuthenticationType.None。
    你能试试下面的那个吗。
    AuthenticationTypes authType = AuthenricationTypes.Secure;

    【讨论】:

    【解决方案2】:

    您确认不是网络问题吗?

    在 PowerShell 中,您可以使用它来测试连接:

    Test-NetConnection myLdapUrl.example -Port 636
    

    如果可行,则可能是来自您服务器的证书不受信任。您可以使用此 PowerShell 代码将证书下载到可以打开和检查的 .cer 文件中:

    $webRequest = [Net.WebRequest]::Create("https://myLdapUrl.example:636")
    try { $webRequest.GetResponse() } catch {}
    $cert = $webRequest.ServicePoint.Certificate
    $bytes = $cert.Export([Security.Cryptography.X509Certificates.X509ContentType]::Cert)
    set-content -value $bytes -encoding byte -path "$home\Downloads\myLdapUrl.example.cer"
    

    这会将myLdapUrl.example.cer 保存到您的“下载”文件夹中。双击它以查看它。如果证书不受信任,那里会有一个明显的警告。如果是这种情况,您需要获取根证书并将其作为受信任的证书安装在将运行此代码的每台计算机上。

    【讨论】:

      猜你喜欢
      • 2010-11-29
      • 2012-08-30
      • 2011-06-10
      • 1970-01-01
      • 2013-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多