使用SSL通过.Net DirectoryServices连接到LDAP

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

我有一些.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. 只需将端口添加到服务器URL 1

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

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

      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
2个回答
0
投票

对于面向安全的连接,我们不能使用AuthenticationType.None。您可以尝试以下一种吗?AuthenticationTypes authType = AuthenricationTypes.Secure;


0
投票

您已确认这不是网络问题吗?

从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保存到您的下载文件夹。双击查看它。如果证书不受信任,将会出现明显的警告。如果是这种情况,您需要获取根证书并将其作为受信任的证书安装在将运行此代码的每台计算机上。

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