从.NET连接到LDAP服务器
我建议使用System.DirectoryServices.Protocols
,以支持连接到Active Directoy以外的LDAP服务器。
不幸的是,我无法正确搜索目录。 我希望能够为用户获得某个属性(例如mail
)。 通过使用DirectorySearcher
类,可以在System.DirectoryServices
命名空间中轻松完成此操作。 如何在System.DirectoryServices.Protocols
命名空间中实现相同的function。 这是我到目前为止所拥有的:
var domainParts = domain.Split('.'); string targetOu = string.Format("cn=builtin,dc={0},dc={1}", domainParts[0], domainParts[1]); string ldapSearchFilter = string.Format("(&(ObjectClass={0})(sAMAccountName={1}))", "person", username); // establish a connection to the directory LdapConnection connection = new LdapConnection( new LdapDirectoryIdentifier(domain), new NetworkCredential() { UserName = username, Password = "MyPassword" }); SearchRequest searchRequest = new SearchRequest( targetOu, ldapSearchFilter, SearchScope.OneLevel, new[] {"mail"});
此代码引发DirectoryOperationException
类型的exception,并显示消息The object does not exist
。
我怀疑我的targetOu
和ldapSearchFilter
变量有问题。
谢谢。
我怀疑主要问题可能是: samAccountName
是一个严格的Windows专用属性,其他LDAP服务器不会知道。
因此,如果您要使用非Active Directory LDAP,则应使用其他内容进行搜索 – 例如sn
(姓氏或姓氏), givenName
(名字),可能是displayName
。
另一个有趣的选择可能是使用ANR(模糊名称解析)搜索 – 在大致中间的SelfADSI上查看此页面 ,其中解释了ANR。
使用ANR,您可以像这样编写查询:
string ldapSearchFilter = string.Format("(&(ObjectCategory={0})(anr={1}))", "person", username);
我还将ObjectClass
更改为ObjectCategory
有两个原因:
-
ObjectCategory
是单值的,例如只包含一个值(ObjectClass
是多值的) -
ObjectCategory
通常是索引的,因此使用ObjectCategory
搜索通常要快得多
这会返回您正在寻找的结果吗?