3

System.DirectoryServices.AccountManagement用来查询 Active Directory 以获取单个用户信息

public UserInfo FindOne(string samUserName)
{
    using (var ctx = new PrincipalContext(ContextType.Domain, "domain.com", "Bob", "pwd"))
    {
        using (UserPrincipal user = UserPrincipal.FindByIdentity(ctx, samUserName))
        {
            if (user != null)
            {
                // get info about Alice into userInfo
                return userInfo;
            }
        }   
    }

    return null;
}

因此,如果我使用var aliceInfo = search.FindOne("alice");,我会从目录中获取信息。现在我需要在给定多个用户登录名的情况下搜索一个目录(1000 多个用户),例如

var userInfos = search.FindMany(/* list of names: alice, jay, harry*/);

如何实现以下方法?

public List<UserInfo> FindMany(List<string> samUserNames)
{
    ...
}
4

2 回答 2

2

尝试这个:

string query = "dc=com,dc=domainController,ou=Users"; //this is just an example query, change it to suit your needs

// create your domain context and define the OU container to search in
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "yourDomain", query);

// define a "query-by-example" principal - here, we search for a UserPrincipal (user)
UserPrincipal qbeUser = new UserPrincipal(ctx);

// create your principal searcher passing in the QBE principal    
PrincipalSearcher srch = new PrincipalSearcher(qbeUser);

return srch.FindAll().Select(p => p as UserPrincipal);

这样您就可以从 AD 中返回所有用户,然后过滤掉不需要的用户。UserPrincipal 有一些与用户相关的属性,例如 Surname 和 Sid,但如果您需要获取 UserPrincipal 没有的值,您可以创建一个扩展方法并访问任何 LDAP 属性:

    public static String GetProperty(this Principal principal, String property)
    {
        DirectoryEntry directoryEntry = principal.GetUnderlyingObject() as DirectoryEntry;
        if (directoryEntry.Properties.Contains(property))
            return directoryEntry.Properties[property].Value.ToString() ?? "";
        else
            return String.Empty;
    }

以下是 LDAP 属性列表:https ://fsuid.fsu.edu/admin/lib/WinADLDAPAttributes.html

于 2013-11-06T14:25:44.100 回答
1

如果您的列表相对较小,最灵活的解决方案可能是循环并逐个查找用户。

替代方案是:

  • 在 LDAP 查询中提供过滤器。由于您没有要过滤的通用属性,因此您需要使用所有用户名创建一个“OR”LDAP 过滤器。这并没有比循环更好地扩展到大量用户。

  • 遍历目录中的所有用户,过滤搜索结果以提取与您的列表匹配的用户。这不能很好地扩展到大型 AD,因为它没有利用 samAccountName 是索引属性这一事实。

于 2013-11-06T14:37:51.377 回答