C#使用.NET Standard 2.0中的自定义属性查询Active Directory

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

如何使用.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 == "..."的用户。

c# active-directory .net-standard .net-standard-2.0 userprincipal
1个回答
1
投票

你不能用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,它返回任何以该人为经理的用户的distinguishedNamemanager属性包含经理帐户的DN)。您可能需要根据需要进行调整。

如果您需要为生成的用户使用UserPrincipal对象,则可以使用此对象(其中distinguishedName变量是用户的DN):

UserPrincipal.FindByIdentity(context, IdentityType.DistinguishedName, distinguishedName)

请记住,manager属性未编入索引。因此,如果这是您唯一的标准(除了(objectClass=user)),那么AD需要查看每个用户以查找匹配项。在您的环境中,这可能会或可能不会非常慢。

就个人而言,我更喜欢直接使用DirectorySearcherDirectoryEntry。我发现整个System.DirectoryServices.AccountManagement命名空间非常慢。我写了一篇关于如何使用System.DirectoryServices命名空间直接加速性能的文章:Active Directory: Better Performance

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