Getting a list of domain group membership for a user account

I was looking for a way to get a list of a user’s associated domain groups. The first pass was to query AD using DirectorySearcher but the PrincipalContext was a less painful route to get what I needed. The method below will get the list of groups that the user belong to. Note that the user returned from the logonUserIdentity.Name will be in domain\user format. We split that apart so we can pass in the user part and also construct a domain.com string. That’s not the exact code I used since we have two different domains but it gets the idea across.

Update: I discovered that I needed to use the user name and password of a domain account for the PrincipalContext call. I installed the application on a virtual machine under IIS 7 and it was failing since the pool identity, NETWORKSERVICE, did not have rights to query AD. I ended up getting an exception:

DirectoryServicesCOMException (0x80072020): An operations error occurred

    public List<string> GetUserDomainGroups(WindowsIdentity logonUserIdentity)
    {
        List<string> groupList = new List<string>();

        string[] user = logonUserIdentity.Name.Split("\\".ToCharArray());
        user[0] += ".com";

        SecurityKey securityKey = GetSecurityKeyFromConfiguration();

        using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, user[0], securityKey.UserName, securityKey.Password))
        {
            using (Principal principal = Principal.FindByIdentity(ctx, user[1]))
            {
                if (principal != null)
                {
                    PrincipalSearchResult<Principal> groups = principal.GetGroups();
                    using (groups)
                    {
                        groupList.AddRange(groups.Select(group => group.SamAccountName));
                    }
                }
            }
        }

        return groupList;
    }