Search code examples
c#active-directoryactive-directory-group

Get the primary group ID


Trying to get all the groups a user belongs to, INCLUDING the primary group:

Doing something like this:

DirectoryEntry entry = new DirectoryEntry(LDAP:/domainXYZ, userx, passwordx); 
DirectorySearcher searcher = new DirectorySearcher(entry);
searcher.Filter = String.Format("(&(objectClass=user)(userPrincipalName={0}{1}))", userY, LDAP://domainXYZ);
SearchResultCollection resultColln= searcher.FindOne();

string actualGroupName =string.empty;
string grp ="";
foreach (SearchResult singleRes in resultColln)
{
   foreach (object value in singleRes.Properties["memberof"])
   {
       grp = value.ToString();
       Console.WriteLine("group:{0} ", grp);
   }
}

This gives me all the groups except the primary group. Is there a way to get the primary group name, using the primaryGroupID in addition to the other groups?


Solution

  • You should run another search using the following search filter

    string.Format("(&(objectCategory=group)(objectClass=group)(primaryGroupToken={0}))", singleRes.Properties["primaryGroupID"]);
    

    primaryGroupToken is a calculated attribute that automatically generated by Active Directory when the group is created. The primaryGroupID assigned to the user is storing this value.

    Actually, if you want a really easy way, I would suggest UserPrincipal.GetGroups is really easy. The only thing is that you can find it only in .NET 3.5 or later.

    using (PrincipalContext context = new PrincipalContext(ContextType.Domain, "yourdomain.com"))
    {
        using (UserPrincipal user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, "YourUser"))
        {
            foreach (Principal p in user.GetGroups())
            {
                 Console.WriteLine(p.Name);
            }
        }
     }
    

    GetGroups returns you only the group that immediately contains your user, including its primary group. If you want to get all the nested groups, you can use GetAuthorizationGroups.