George Polevoy
George Polevoy

Reputation: 7681

Query ActiveDirectory for groups, owned by groups, where i'm a member

I have several groups, each group is owned by a group.

group1 managed by group1_owners (not sure if it's a naming convention) group2 managed by group2_owners ...

given a user, i need to find all groups, which are owned by the groups, where the user is a member.

Is it possible to find such groups in a single query?

Here is what i'm using to check if the user is in the owners group of a group, but not sure it's efficient.

var domain = new DirectoryEntry("LDAP://" + domainName, null, null, AuthenticationTypes.Secure););
DirectorySearcher searcher = new DirectorySearcher(domain);
searcher.Filter = string.Format("(&(objectCategory=group)(cn={0}))", group);
searcher.PropertiesToLoad.Add("managedby");
searcher.SearchScope = SearchScope.Subtree;
SearchResult groupSR = searcher.FindOne();

var ownerGroup = new DirectoryEntry("LDAP://" + groupSR.Properties["managedby"][0],null, null, AuthenticationTypes.Secure);
PropertyValueCollection members = ownerGroup.Properties["member"];
for(i=0;i<members.Count;i++)
{
 if( members[i].ToString()==userName) .......
}

Upvotes: 1

Views: 1505

Answers (1)

JPBlanc
JPBlanc

Reputation: 72630

Given a user, you need to find all groups, which are managed by the groups, where the user is a member.

I don't think you can do it in one search. But you can first search for all the groups a user is member and them search all groups managed by these groups.

/* Connection to Active Directory
 */
DirectoryEntry deBase = new DirectoryEntry("LDAP://WM2008R2ENT:389/dc=dom,dc=fr");

/* Search for all groups a user belongs to
 */
string givenUser = "CN=user1 Users,OU=MonOu,DC=dom,DC=fr";
DirectorySearcher dsLookFor1 = new DirectorySearcher(deBase);
dsLookFor1.Filter = string.Format("(member={0})", givenUser);
dsLookFor1.SearchScope = SearchScope.Subtree;
dsLookFor1.PropertiesToLoad.Add("distinguishedName");

SearchResultCollection belongToGroups = dsLookFor1.FindAll();
foreach (SearchResult srGroupBelongTo in belongToGroups)
{
  Console.WriteLine("{0}", srGroupBelongTo.Properties["distinguishedName"][0]);

  /* Search for all groups managed by a group
   */
  DirectorySearcher dsLookFor2 = new DirectorySearcher(deBase);
  dsLookFor2.Filter = string.Format("(&(objectClass=group)(managedBy={0}))", srGroupBelongTo.Properties["distinguishedName"][0]);
  dsLookFor2.SearchScope = SearchScope.Subtree;
  dsLookFor2.PropertiesToLoad.Add("distinguishedName");

  SearchResultCollection managedByGroups = dsLookFor2.FindAll();
  foreach (SearchResult srGroupManagedBy in managedByGroups)
  {
    Console.WriteLine("\t{0}", srGroupManagedBy.Properties["distinguishedName"][0]);
  }
}

Upvotes: 1

Related Questions