c# - 如何在给定多个用户名的情况下查询 Active Directory?

标签 c# active-directory directoryservices

我使用 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)
{
    ...
}

最佳答案

试试这个:

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

关于c# - 如何在给定多个用户名的情况下查询 Active Directory?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19814371/

相关文章:

c# - 从 Google 日历中检索条目

security - 在合作伙伴公司的 Active Directory 实例之间建立信任关系是否有意义?

c# - 将 Excel 范围转换为 C# 数组

c# - 通过 JQuery 使用 WCF POST 的 400 错误请求 HTTP 响应

C# 安全 token 错误 3242

c# - Active Directory 中的搜索过滤器无效

c# - 从 PrincipalContext 中查找域组件

c# - 从 Active Directory 获取 GUID 或 native GUID

c# - 使用C#4.0运行Python脚本报错non-ascii char

java - 使用 ActiveDirectoryLdapAuthenticationProvider 和嵌入式 ldif 的 Spring 身份验证