我有一個函數,它獲取組的參數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