优化广告搜索-获得组成员

本文关键字:组成员 搜索 优化 | 更新日期: 2023-09-27 18:18:08

是否可以只查询来自AD的group的成员?

现在我使用以下代码:

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

问题是我的组有大量的用户(超过5万),因此查询工作非常长。同时,传输的数据量也很大。

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

编辑

我最终得到了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]);
        }
    }
}

优化广告搜索-获得组成员

我建议使用较低级别的DirectoryServices.Protocols命名空间而不是DirectoryServices.AccountManagement

我(以及其他许多人)在AccountManagement库中遇到的问题是缺乏自定义和配置。话虽如此,这就是我如何通过活动目录进行搜索,并利用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;

这可能不是您所需要的,但正如您所看到的,您将有更多的灵活性来更改和修改搜索条件。我使用这段代码来搜索大量的域结构,它几乎是即时的,即使有大量的用户和组。