如何使用 C# 中的 DirectoryEntry 成功连接到本地主机 LDAP 域?

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

我在 CLI 中通过 WSL 在 Windows 上运行 Ubuntu,并且我在 Ubuntu 上配置了 LDAP(OpenLDAP:slapd)如下:

BASE    dc=example,dc=com
URI     ldap://localhost

当我在 Ubuntu 上运行以下命令时,它显示了我在 LDAP 服务器上设置的用户和组的结构,这表明我能够使用我的 test 用户连接到服务器:

ldapsearch -D "cn=test,ou=Department,dc=example,dc=com" -w test -b 'dc=example,dc=com' '(objectclass=*)'

在我的 Windows 主机上,我在打开或关闭 Windows 功能 窗口中选中了Active Directory Lightweight Directory Services 框,这允许使用 LDP.exe。在 LDP.exe 中,我还可以连接 LDAP 服务器,方法是选择 Connection > Bind > 为 User 填写“cn=test,ou=Department,dc=example,dc=com” 字段和 Password 字段的“测试” > 并在单击 OK 之前选择 Simple bind

点击OK后,LDP.exe反馈如下:

我还能够在我的 C# 代码中从 LDAP 服务器检索信息——例如:

de = new DirectoryEntry("LDAP://localhost:389/ou=Department,dc=example,dc=com");
de.AuthenticationType = AuthenticationTypes.None;
var childNames = new List<string>();
foreach(DirectoryEntry child in de.Children)
{
    childNames.Add(child.Name.ToString());
}

以上内容让我确信 LDAP 服务器配置正确并且我能够在我的代码中访问它,但是当我修改代码如下时,我无法通过上述test 用户连接:

var de = new DirectoryEntry("LDAP://localhost/OU=Department,DC=example,DC=com", username, password);
var childNames = new List<string>();
foreach(DirectoryEntry child in de.Children)
{
    childNames.Add(child.Name.ToString());
}

当我运行上面的代码时,在 foreach 部分出现错误,提示“用户名或密码不正确。”

我已经尝试将usernamepassword变量设置为我能想到或在网上找到的所有方式,例如将密码设置为“test”或其SSHA哈希,并将username设置为“test "、"cn=test"、"example.com\test" 或 "[email protected]",但我在运行代码时一直收到“用户名或密码不正确”的消息。

我还尝试了多种身份验证形式的用户名和密码组合,例如:

var de = new DirectoryEntry("LDAP://localhost/OU=Department,DC=example,DC=com", username, password, AuthenticationTypes.Secure);

但是我一直找不到正确的配置。如何配置代码以便接受用户名和密码组合?

ldap openldap c#-7.0 directoryentry slapd
2个回答
0
投票

你说:

我在 CLI 中通过 WSL 在 Windows 上运行 Ubuntu,并且我在 Ubuntu 上配置了 LDAP(OpenLDAP:slapd)

然后:

在我的 Windows 主机上,我在“打开或关闭 Windows 功能”窗口中选中了 Active Directory Lightweight Directory Services 框

这意味着您现在有两个 LDAP 服务器在同一台机器上运行。我猜 AD LDS 实例优先,这就是给你“用户名或密码不正确”错误的实例。

如果你想连接到你的 OpenLDAP 实例,你需要禁用 Active Directory Lightweight Directory Services。如果你想保留LDP,你可以在卸载AD LDS之前把Windows\System32文件夹下的ldp.exe文件复制出来,然后再复制回来。


0
投票

显然,用户名必须包含完整的 DN。下面的代码有效:

string username = "cn=test,ou=Department,dc=example,dc=com", password = "test";
var de = new DirectoryEntry("LDAP://localhost:389/ou=Department,dc=example,dc=com", username, password, AuthenticationTypes.None);
childNames = new List<string>();
foreach(DirectoryEntry child in de.Children)
{
    childNames.Add(child.Name.ToString());
}

在 Microsoft 页面上,据说 AuthenticationTypes.None “等于零,这意味着在 LDAP 提供程序中使用基本身份验证(简单绑定)。” 我首先假设 AuthenticationTypes.None 意味着用户名并且不会检查密码的正确性(与AuthenticationTypes.Anonymous一样,但正在检查它们。

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