我有一个函数,它获取组的参数Distringuished name
,并使用SearchRequest
查询和SearchResponse
返回给定组内的嵌套组或组。当我使用DirectoryEntry
时,代码正常工作,但在使用LdapConnection
类时失败。有必要使用LdapConnection
类。请在下面找到代码片段:如何在c#中的System.DirectoryServices.Protocol中获取嵌套组(子组)?
public static void GetNestedGroups(string strGroupDN)
{
var _currentDomainofLoggedinUser = Domain.GetComputerDomain();
var currentDomainofLoggedinUser = Domain.GetComputerDomain();
var currentDomainController = currentDomainofLoggedinUser.FindDomainController(); //Gets the current Domain controller
var domainName = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName;
string strPath = "LDAP://" + currentDomainController.Name; //Gets the current domain controller name
AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
using (LdapConnection ldap = new LdapConnection(new LdapDirectoryIdentifier(domainName, 636)))
{
ldap.AuthType = AuthType.Basic;
ldap.SessionOptions.SecureSocketLayer = false;
var s = new SecureString();
NetworkCredential network = new NetworkCredential(WindowsIdentity.GetCurrent().Name, s);
string ldapSearchFilter = String.Format
("(&(memberOf={0})(objectClass=group))", strGroupDN);
NetworkCredential cred = CredentialCache.DefaultNetworkCredentials;
ldap.Bind(network);
string[] attributesToReturn = new string[] { "distinguishedName" };
SearchRequest searchRequest = new SearchRequest(strGroupDN, ldapSearchFilter, SearchScope.OneLevel, attributesToReturn);
searchRequest.DistinguishedName =
strGroupDN;
searchRequest.Filter = String.Format
("(&(memberOf={0})(objectClass=group))", strGroupDN);
SearchResponse response = (SearchResponse)ldap.SendRequest(searchRequest);
if (response != null && response.Entries.Count > 0)
{
SearchResultEntry obj = response.Entries[0];
var groupCount = ((System.Collections.CollectionBase)(obj.Attributes["memberOf"])).Count;
foreach (SearchResultEntry entry in response.Entries)
{
var groupName = entry.DistinguishedName;
_subGroupList.Add(groupName.ToString().Split('=')[1].Split(',')[0]);
GetNestedGroups(groupName);
}
}
}
}
在响应中,它不给任何东西。 (在DirectoryEntry
的情况下,它确实提供了结果)
请注意,在AD中,我可以同时创建GroupA的GroupB和GroupB成员的GroupA成员。在这里,你将会有一个无限的递归 – oldovets
并注意memberOf属性不包含来自其他域的组(如果你有)。 – oldovets