Search code examples
c#active-directoryuserprincipal

get all Active Directory groups a user is member in


I am looking for a simple way to get all Active Directory Groups a given User is member in. There are two methods in UserPrincipal, but both don't match this requirement:

  • GetGroups(): returns all groups, but not recursive:

    This method returns only the groups of which the principal is directly a member; no recursive searches are performed.

  • GetAuthorizationGroups(): works recursive, but returns only security groups (no distribution groups)

    This function only returns groups that are security groups; distribution groups are not returned.

Unfortunately, I am not able to find something like GetAllGroups() or GetDistributionGroups(). Is there a short solution to get security and distribution groups recursively?


Solution

  • I ended up writing the method myself, it is suprisingly short.
    Most helpful is that Principal itself contains the .GetGroups()-Method and therefore it is easy to write a recursive Method that returns all Groups of the given User- oder GroupPrincipal.

    The code:

    private static HashSet<GroupPrincipal> GetAllGroups(Principal principal)
    {
        Dictionary<string, GroupPrincipal> groups = new Dictionary<string, GroupPrincipal>();
        foreach (GroupPrincipal group in principal.GetGroups())
        {
            groups[group.Sid.ToString()] = group;
            foreach (GroupPrincipal childGroup in GetAllGroups(group))
            {
                groups[childGroup.Sid.ToString()] = childGroup;
            }
        }
        return new HashSet<GroupPrincipal>(groups.Values);
    }