0

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?

Breeze
  • 2,010
  • 2
  • 32
  • 43

1 Answers1

0

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);
}
Breeze
  • 2,010
  • 2
  • 32
  • 43
  • Great solution for AD groups! But be aware that neither local groups nor predefined security principals are returned. So for some scenarios it should be combined with the other aproaches (something like `WindowsIdentity.GetCurrent().Groups;`). – Sebastian Sep 28 '16 at 08:11