优化AD搜索 - 获取组成员

时间:2013-06-13 13:52:07

标签: c# .net active-directory ldap

是否可以只查询组中的成员,这也是来自AD的组?

现在我使用以下代码:

var group = GroupPrincipal.FindByIdentity(ctx, identityType, domainGroup);
if (null != group)
{
    var subGroups = group.GetMembers().Where(g => g is GroupPrincipal).Select(g => g.Name);
................
}

问题是我的群组有大量用户(超过50 000),因此查询工作时间非常长。此外,还传输了大量数据。

如何在单个请求中仅查询直接子组(而非用户)?

编辑

我最终得到了DirectorySearcher。这是我完成的代码:

using (var searcher = new DirectorySearcher(string.Format("(&(objectCategory=group)(objectClass=group)(memberof={0}))", group.DistinguishedName), new[] { "cn" }))
{
    searcher.PageSize = 10000;
    var results = SafeFindAll(searcher);

    foreach (SearchResult result in results)
    {
        for (int i = 0; i < result.Properties["cn"].Count; i++)
        {
            subGroups.Add((string)result.Properties["cn"][i]);
        }
    }
}

1 个答案:

答案 0 :(得分:2)

我建议使用较低级DirectoryServices.Protocols命名空间而不是DirectoryServices.AccountManagement这样的内容。

我在AccountManagement库中遇到的问题(以及其他许多问题)是缺乏自定义和配置。话虽这么说,这就是我在Active Directory中搜索的方式,同时也使用了System.DirectoryServices.Protocols.SearchScope

//Define the connection
var ldapidentifier = new LdapDirectoryIdentifier(ServerName, port);
var ldapconn = new LdapConnection(ldapidentifier, credentials);

//Set some session options (important if the server has a self signed cert or is transferring over SSL on Port 636)
ldapconn.SessionOptions.VerifyServerCertificate += delegate { return true; };
ldapconn.SessionOptions.SecureSocketLayer = true;

//Set the auth type, I'm doing this from a config file, you'll probably want either Simple or Negotatie depending on the way your directory is configured.
ldapconn.AuthType = config.LdapAuth.LdapAuthType;

这是DirectoryServices真正开始发光的地方。您可以轻松定义过滤器以按特定组或子组进行搜索。你可以这样做:

string ldapFilter = "(&(objectCategory=person)(objectclass=user)(memberOf=CN=All Europe,OU=Global,dc=company,dc=com)";  

//Create the search request with the domain, filter, and SearchScope. You'll most likely want Subtree here, but you could possibly use Base as well. 
var getUserRequest = new SearchRequest(Domain, ldapFilter, SearchScope.Subtree)                                        

//This is crucial in getting the request speed you want. 
//Setting the DomainScope will suppress any refferal creation during the search
var SearchControl = new SearchOptionsControl(SearchOption.DomainScope);
getUserRequest.Controls.Add(SearchControl);

//Now, send the request, and get your array of Entry's back
var Response = (SearchResponse)ldapconn.SendRequest(getUserRequest);

SearchResultEntryCollection Users = Response.Entries;

这可能不是完全您需要的东西,但正如您所看到的,您可以更灵活地更改和修改搜索条件。我使用此代码搜索大量域结构,即使有大量用户和组,它也几乎是即时的。

相关问题