如何使用.NET Standard2.0中的自定义属性查询公司的Active Directory?例如,如果我想使用给定属性进行查询,我的代码如下所示:
FSharpOption<UserPrincipal> TryGetUser(SecurityIdentifier sid)
{
using (var context = new PrincipalContext(ContextType.Domain))
{
var user = UserPrincipal.FindByIdentity(context, IdentityType.Sid, sid.Value);
if (user == null)
return FSharpOption<UserPrincipal>.None;
return FSharpOption<UserPrincipal>.Some(user);
}
}
现在,我想查询一个名为"manager"
的自定义属性,它是一个字符串。我想搜索所有拥有manager == "..."
的用户。
你不能用UserPrincipal
做,PrincipalSearcher
只会让你搜索UserPrincipal
暴露的属性。你必须直接使用DirectorySearcher
(无论如何PrincipalSearcher
在幕后使用)。
这是你要做的一个例子:
public IEnumerable<string> GetUsersWithManager(string managerDn) {
var search = new DirectorySearcher(new DirectoryEntry()) {
Filter = $"(&(objectClass=user)(manager={managerDn}))"
};
search.PropertiesToLoad.Add("distinguishedName");
using (var results = search.FindAll()) {
foreach (SearchResult result in results) {
if (result.Properties.Contains("mail")) {
yield return (string) result.Properties["distinguishedName"][0];
}
}
}
}
该参数是经理的distinguishedName
,它返回任何以该人为经理的用户的distinguishedName
(manager
属性包含经理帐户的DN)。您可能需要根据需要进行调整。
如果您需要为生成的用户使用UserPrincipal
对象,则可以使用此对象(其中distinguishedName
变量是用户的DN):
UserPrincipal.FindByIdentity(context, IdentityType.DistinguishedName, distinguishedName)
请记住,manager
属性未编入索引。因此,如果这是您唯一的标准(除了(objectClass=user)
),那么AD需要查看每个用户以查找匹配项。在您的环境中,这可能会或可能不会非常慢。
就个人而言,我更喜欢直接使用DirectorySearcher
和DirectoryEntry
。我发现整个System.DirectoryServices.AccountManagement
命名空间非常慢。我写了一篇关于如何使用System.DirectoryServices
命名空间直接加速性能的文章:Active Directory: Better Performance