How to avoid infinite loop due to cyclic group membership of Active Directory Groups? RRS feed

  • Question

  • Hi All,

    I have written a code to check if given user is a member of particular user group. I want to cover indirect membership as well, arisen due to nested grouping. As cyclic grouping is allowed (e.g. Group A is member of Group B and vice-verse), my code is running into infinite loop.

    Is there anyways to avoid this infinite looping?

    Thanking you in advance..

    Saturday, October 15, 2011 8:07 AM

All replies

  • You need to write your logic to deal with the potential of this happening the method i use is just to store the DN of Group as you process it in a hashtable and then use the hashtable to check if the group has allready been enuerated. You can also use a seperate hash to ensure if a user is in two groups that they only get counted once. eg in powershell and ASDI something like

    $repeathashGroup = @{ }
    $repeathashUser = @{ }
    function Get-member($GroupName){
    $Grouppath = "LDAP://" + $GroupName
    $groupObj = [ADSI]$Grouppath
    foreach($member in $groupObj.Member){
    $userPath = "LDAP://" + $member
    $UserObj = [ADSI]$userPath
    if($UserObj.groupType.Value -eq $null){
    if($repeathashUser.ContainsKey($UserObj.distinguishedName.ToString()) -eq $false){
    if($repeathashGroup.ContainsKey($UserObj.distinguishedName.ToString()) -eq $false){


    Monday, October 17, 2011 5:28 AM
  • Hi,

    with ActiveDirectory, you can also bind to the user object and request the tokenGroups property. It contains an array of byte arrays which you can parse using the SecurityIdentifier class.

    The tokenGroups property contains all direct and indirect group memberships. (See http://msdn.microsoft.com/en-us/library/windows/desktop/ms680275(v=vs.85).aspx).

    var sids = new IdentityReferenceCollection();
    foreach (byte[] group in tokenGroups)
         sids.Add(new SecurityIdentifier(group, 0));

    After that, you can translate these SecurityIdentifiers to NTAccount entitites using

    var accounts = sids.Translate(typeof(NTAccount));

    Kind regards,

    If you get your question answered, please come back and mark the reply as an answer.
    If you are helped by an answer to someone else's question, please mark it as helpful.

    Monday, October 17, 2011 4:22 PM