Get all group names of a windows domain user

Active Directory

From Command Line

Run the following from a command line


net user [username] /domain

It returns a list of domain groups of which the user is a member.

Programatically

We need to detect the current domain name, by quering LDAP://RootDSE, then we use it to search for all the groups to which the user belongs.


public class GroupDetect
{
        public static (bool, List<string>) GetTokenGroups(string username)
        {
             bool result = false;
            var userGroups = new List<string>();

            try
            {
                var rootDSE = new DirectoryEntry("LDAP://RootDSE");
                string defaultNamingContext = (string)rootDSE.Properties["defaultNamingContext"].Value;
                rootDSE.Dispose();

                SearchResult sr = default(SearchResult);

                using var domainDE = new DirectoryEntry($"LDAP://{defaultNamingContext}",
                    null, null, AuthenticationTypes.Secure);

                using var searcher = new DirectorySearcher(domainDE);             

                searcher.Filter = $"(&(objectClass=user)(sAMAccountName={username}))";

                sr = searcher.FindOne();

                if (sr != null)
                {

                    using DirectoryEntry user = sr.GetDirectoryEntry();

                    user.RefreshCache(new string[] { "tokenGroups" });

                    for (int i = 0; i < user.Properties["tokenGroups"].Count; i++)
                    {
                        var sid = new SecurityIdentifier((byte[])user.Properties["tokenGroups"][i], 0);                 

                        try
                        {
                            NTAccount nt = (NTAccount)sid.Translate(typeof(NTAccount));
                            userGroups.Add(nt.Value.Split('\\').Last().ToLower());
                        }
                        catch
                        {

                        }

                    }  

                }

            }
            catch (Exception ex)
            {

            }

            return (result, userGroups);

        }

    }

Post a Comment

Previous Post Next Post