Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you find an Active Directory User's Primary Group in C#?

I am working on an application that manages user accounts in Active Directory. I am using the System.DirectoryServices.AccountManagement namespace whereever possible, but I can't figure out how to determine a user's primary group. When I try to remove a group that is the user's primary group I get an exception. Here is my current code:

private void removeFromGroup(UserPrincipal userPrincipal, GroupPrincipal groupPrincipal) {
    TODO: Check to see if this Group is the user's primary group.
    groupPrincipal.Members.Remove(userPrincipal);
    groupPrincipal.Save();
}

Is there a way to get the name of the user's primary group so I can do some validation before trying to remove the user from this group?

like image 548
Andy May Avatar asked Oct 14 '22 14:10

Andy May


1 Answers

It's quite a messy and involved business - but this code snippet is from my BeaverTail ADSI Browser which I wrote completely in C# (in the .NET 1.1 days) and is known to work - not pretty, but functional:

private string GetPrimaryGroup(DirectoryEntry aEntry, DirectoryEntry aDomainEntry)
{
   int primaryGroupID = (int)aEntry.Properties["primaryGroupID"].Value;
   byte[] objectSid = (byte[])aEntry.Properties["objectSid"].Value;

   StringBuilder escapedGroupSid = new StringBuilder();

   // Copy over everything but the last four bytes(sub-authority)
   // Doing so gives us the RID of the domain
   for(uint i = 0; i < objectSid.Length - 4; i++)
   {
      escapedGroupSid.AppendFormat("\\{0:x2}", objectSid[i]);
   }

   //Add the primaryGroupID to the escape string to build the SID of the primaryGroup
   for(uint i = 0; i < 4; i++)
   {
      escapedGroupSid.AppendFormat("\\{0:x2}", (primaryGroupID & 0xFF));
      primaryGroupID >>= 8;
   }

   //Search the directory for a group with this SID
   DirectorySearcher searcher = new DirectorySearcher();
   if(aDomainEntry != null)
   {
       searcher.SearchRoot = aDomainEntry;
   }

   searcher.Filter = "(&(objectCategory=Group)(objectSID=" + escapedGroupSid.ToString() + "))";
   searcher.PropertiesToLoad.Add("distinguishedName");

   return searcher.FindOne().Properties["distinguishedName"][0].ToString();
}

Hope this helps.

Marc

like image 93
marc_s Avatar answered Oct 18 '22 13:10

marc_s