如何在C#中通过DirectoryEntry成功连接本地LDAP域?
问题:C# DirectoryEntry 无法通过OpenLDAP用户认证
环境与配置
- 运行环境:Windows通过WSL运行Ubuntu,部署OpenLDAP(slapd),LDAP客户端配置如下:
BASE dc=example,dc=com URI ldap://localhost
已验证的成功连接方式
- Ubuntu本地命令行验证:
执行以下命令可正常获取LDAP服务器上的用户和组结构:ldapsearch -D "cn=test,ou=Department,dc=example,dc=com" -w test -b 'dc=example,dc=com' '(objectclass=*)' - Windows主机LDP.exe验证:
启用「Active Directory Lightweight Directory Services」后,打开LDP.exe,通过「Connection」>「Bind」选择Simple bind,填入用户cn=test,ou=Department,dc=example,dc=com和密码test,可成功绑定。 - C#匿名访问验证:
以下代码可正常检索LDAP目录信息(匿名访问模式):var 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()); }
失败的认证尝试
当使用带用户名密码参数的DirectoryEntry构造函数时,遍历Children时始终抛出「用户名或密码不正确」错误:
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()); }
已尝试的配置:
- 用户名格式:
test、cn=test、example.com\\test、test@example.com - 密码:明文
test、SSHA哈希值 - 认证类型:指定
AuthenticationTypes.Secure等多种类型
所有尝试均无法通过认证。
求助
如何配置C#代码,才能让test用户的用户名密码组合被OpenLDAP服务器正确接受?
内容的提问来源于stack exchange,提问作者HasQuestionsAndAnswers
相关产品推荐
相关产品推荐

