Return a list of all Active Directory groups a user belongs to in string[ ]

13,634

Solution 1

This should do the trick.

using System.DirectoryServices.AccountManagement;

public static string[] GetGroups(string username)
{
    string[] output = null;

    using (var ctx = new PrincipalContext(ContextType.Domain))
    using (var user = UserPrincipal.FindByIdentity(ctx, username))
    {
        if (user != null)
        {
            output = user.GetGroups() //this returns a collection of principal objects
                .Select(x => x.SamAccountName) // select the name.  you may change this to choose the display name or whatever you want
                .ToArray(); // convert to string array
        }
    }

    return output;
}

Solution 2

In case you want to return a bool value if user belongs to a group, here it go:

 string[] output = null;
            using (var ctx = new PrincipalContext(ContextType.Domain, domain))
            using (var user = UserPrincipal.FindByIdentity(ctx, username))
            {
                if (user != null)
                {
                    output = user.GetGroups()
                        .Select(x => x.SamAccountName)
                        .ToArray();
                }

                bool isMember = output.Any(groupName.Contains);
            }
Share:
13,634
user2224493
Author by

user2224493

Updated on June 17, 2022

Comments

  • user2224493
    user2224493 almost 2 years

    I need to return all Active Directory groups a user belongs to but in string[ ], so I can use the result in Generic Principal.

    I am not sure if to cast results? Please help!

    string[] roles = new string[] {  
    helper.GetActiveDirectoryGroups(User.Identity.Name) };
    
    GenericPrincipal principal = new GenericPrincipal(identity,roles);
    
     public string[] GetActiveDirectoryGroups(string userName)
        {
              //code here
    
        }
    
  • user2224493
    user2224493 over 8 years
    Yes indeed David! Exactly what i was looking for. The ToArray() converts the collection of principal objects to a string array.
  • Detilium
    Detilium about 7 years
    Works like a charm!
  • Issa Fram
    Issa Fram almost 6 years
    This works with the exception of not recursively checking groups
  • Kelvin
    Kelvin over 5 years
    if you want to get all the nested groups instead of GetGroups() use GetAuthorizationGroups()