问题描述
我被推荐使用 System.DirectoryServices.Protocols
来支持连接到 Active Directory 以外的 LDAP 服务器 这里.
不幸的是,我无法正确搜索目录.我希望能够为用户获取某个属性(例如 mail
).这可以通过使用 DirectorySearcher
类在 System.DirectoryServices
命名空间中轻松完成.如何在 System.DirectoryServices.Protocols
命名空间中实现相同的功能.到目前为止,这是我所拥有的:
I've been recommended to use System.DirectoryServices.Protocols
to be able to support connecting to LDAP servers other than Active Directoy here.
Unfortunately, I have not been able to search the directory properly. I'd like to be able to get a certain attribute for a user (e.g. mail
). This is easily done in System.DirectoryServices
namespace by using DirectorySearcher
class. How can I achieve the same in System.DirectoryServices.Protocols
namespace. Here's what I have so far:
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
类型的异常,并带有消息 对象不存在
.
This code raises exception of type DirectoryOperationException
with message The object does not exist
.
我怀疑我的 targetOu
和 ldapSearchFilter
变量有问题.
I suspect there's something wrong with my targetOu
and ldapSearchFilter
variables.
谢谢.
推荐答案
我怀疑主要问题可能是:samAccountName
是其他 LDAP 服务器不知道的严格的仅限 Windows 的属性.
I suspect the main problem might be: samAccountName
is a strictly Windows-only attribute that other LDAP servers won't know about.
因此,如果您要使用非 Active Directory LDAP,您应该使用其他东西进行搜索 - 例如sn
(用于姓氏或姓氏),givenName
(名字),可能是 displayName
.
So if you're going against a non-Active Directory LDAP, you should use something else for searching - e.g. sn
(for surname or last name), givenName
(first name), possibly displayName
.
另一个有趣的选择可能是使用 ANR(模糊名称解析)搜索 - 请参阅 SelfADSI 上的这个 页面 大致在中间,这里解释了 ANR.
Another interesting option might be to use ANR (ambiguous name resolution) searches - see this page on SelfADSI roughly in the middle, where ANR is explained.
使用 ANR,您可以这样编写查询:
With ANR, you would write your query like this:
string ldapSearchFilter =
string.Format("(&(ObjectCategory={0})(anr={1}))", "person", username);
我还将 ObjectClass
更改为 ObjectCategory
有两个原因:
I also changed ObjectClass
to ObjectCategory
for two reasons:
ObjectCategory
是单值的,例如只包含一个值(ObjectClass
是多值的)ObjectCategory
通常会被索引,因此使用ObjectCategory
搜索通常会快很多
ObjectCategory
is single-valued, e.g. only contains a single value (ObjectClass
is multi-valued)ObjectCategory
is typically indexed, and thus searches are typically a lot faster usingObjectCategory
这会返回您正在寻找的结果吗?
Does this return the results you're looking for?
这篇关于从 .NET 连接到 LDAP 服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!