gpt4 book ai didi

c# - 从 .NET 连接到 LDAP 服务器

转载 作者:行者123 更新时间:2023-11-30 16:26:33 24 4
gpt4 key购买 nike

有人建议我使用 System.DirectoryServices.Protocols 以支持连接到 Active Directoy 以外的 LDAP 服务器 here .
不幸的是,我无法正确搜索目录。我希望能够为用户获取某个属性(例如 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 变量有问题。

谢谢。

最佳答案

我怀疑主要问题可能是:samAccountName 是其他 LDAP 服务器不知道的严格仅限 Windows 的属性。

因此,如果您要反对非 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
  • 搜索通常要快得多

这是否会返回您要查找的结果?

关于c# - 从 .NET 连接到 LDAP 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8700115/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com