Mahesh KP
Mahesh KP

Reputation: 6446

Domain Users group is not getting for an active directory user

We are using the following code to get the groups of an active directory user.

StringCollection groups = new StringCollection();

try
{
   using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, domainName, userName, password))
   {
      //find user roles
      UserPrincipal user = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, loginUserName);

      if (user != null)
      {
         DirectoryEntry de = (DirectoryEntry)user.GetUnderlyingObject();
         object obGroups = de.Invoke("Groups");                        

         foreach (object ob in (IEnumerable)obGroups)
         {
            DirectoryEntry obGpEntry = new DirectoryEntry(ob);                            
            groups.Add(obGpEntry.Name);
         }    
      }
   }
}
catch (Exception e)
{
}

This is working almost as expected. But while we checking the users with Domain Users group, the method didn't return the group name. Some users are only with this Domain Users group and while we calling this method for such users its returning an empty group.

Any suggestions please..

Upvotes: 1

Views: 2681

Answers (1)

marc_s
marc_s

Reputation: 755491

It's a well-known and documented "omission" that the so called primary group is not returned from the Groups method in this code. There are some rather cryptic ways around this - or try this other approach:

if you're on .NET 3.5 and up, you should check out the System.DirectoryServices.AccountManagement (S.DS.AM) namespace. Read all about it here:

Basically, you can define a domain context and easily find users and/or groups in AD:

// set up domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

// find a user
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "SomeUserName");

if(user != null)
{
   // the call to .GetAuthorizationGroups() will return **all** groups that
   // user is a member of - including the primary group and all nested 
   // group memberships, too!
   var result = user.GetAuthorizationGroups();
}

The new S.DS.AM makes it really easy to play around with users and groups in AD!

Update: if you insist on using the old legacy technology, check out this blog post by Ryan Dunn which explains in great detail how to get the primary group for an AD account in C#.

Upvotes: 2

Related Questions