Get user groups in AD with nested groups

2.6k views Asked by At

I don't know if "nested" is the word for what I need, but here's the explanation:

I have a user, "John". "John" is member of the group "A". Group "B" has group "A" as a member.

So, transitively, "John" should also be member of the group "B".

When I retrieve the John's group, I only get "A", and not "B", doing it like this:

DirectorySearcher searcher = new DirectorySearcher();
DirectoryEntry rootEntry = new DirectoryEntry(_ldap, _loginName, _password, AuthenticationTypes.ReadonlyServer);

searcher.SearchRoot = rootEntry;
searcher.SearchScope = SearchScope.Subtree;
searcher.Filter = "(&(sAMAccountName=" + filter.Split('\\')[1] + ")(objectClass=user))";
searcher.PropertiesToLoad.Add("memberOf");
searcher.PropertiesToLoad.Add("displayname");

SearchResult sr = searcher.FindOne();

How can I achieve this?

Thank you!

1

There are 1 answers

1
Nicole On BEST ANSWER

I ended up using the "tokenGroups" property of the user, which seems to return all the groups the user is in, even the ones in which he is member transitively.

here's my code:

DirectorySearcher searcher = new DirectorySearcher();
DirectoryEntry rootEntry = new DirectoryEntry(_ldap, _loginName, _password, AuthenticationTypes.ReadonlyServer);

searcher.SearchRoot = rootEntry;
searcher.SearchScope = SearchScope.Subtree;
searcher.Filter = "(&(sAMAccountName=" + filter.Split('\\')[1] + ")(objectClass=user))";
searcher.PropertiesToLoad.Add("memberOf");
searcher.PropertiesToLoad.Add("displayname");

SearchResult sr = searcher.FindOne();
DirectoryEntry userDirectoryEntry = result.GetDirectoryEntry();
userDirectoryEntry.RefreshCache(new string[] { "tokenGroups" });

foreach (byte[] byteEntry in userDirectoryEntry.Properties["tokenGroups"])
{
   if (CompareByteArrays(byteEntry, objectSid))
   {
         isMember = true;
         break;
   }
}

It's a mix of this and this link, where objectSid is the objectSID of the group which I find by name.

Thanks a lot for your help!