从.NET连接到LDAP服务器

问题描述 投票:3回答:1

我被建议使用System.DirectoryServices.Protocols来支持连接到Active Directoy here以外的LDAP服务器。 不幸的是,我无法正确搜索目录。我希望能够为用户获得某个属性(例如mail)。这可以通过使用System.DirectoryServices类在DirectorySearcher命名空间中轻松完成。如何在System.DirectoryServices.Protocols命名空间中实现相同的功能。这是我到目前为止所拥有的:

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引发类型The object does not exist的异常。

我怀疑我的targetOuldapSearchFilter变量有问题。

谢谢。

c# .net ldap directoryservices
1个回答
3
投票

我怀疑主要问题可能是:samAccountName是一个严格的Windows专用属性,其他LDAP服务器不会知道。

因此,如果您要使用非Active Directory LDAP,则应使用其他内容进行搜索 - 例如sn(姓氏或姓氏),givenName(名字),可能是displayName

另一个有趣的选择可能是使用ANR(模糊名称解析)搜索 - 大致在中间看到这个page on SelfADSI,其中解释了ANR。

使用ANR,您可以像这样编写查询:

string ldapSearchFilter = 
   string.Format("(&(ObjectCategory={0})(anr={1}))", "person", username);

我还将ObjectClass改为ObjectCategory有两个原因:

  • ObjectCategory是单值的,例如只包含一个值(ObjectClass是多值的)
  • ObjectCategory通常被编入索引,因此使用ObjectCategory搜索通常要快得多

这会返回您正在寻找的结果吗?

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