views:

41

answers:

2

What is the best way to retrieve a list of groups a user belongs to from a windows service?

List<string> groups = new List<string>();

foreach (IdentityReference ir in new WindowsIdentity(name).Groups)
{
     SecurityIdentifier sid = new SecurityIdentifier(ir.Value);
     NTAccount ntAccount = (NTAccount)sid.Translate(typeof(NTAccount));
     groups.Add(ntAccount.ToString());
}

I tried to use above code but it raised the following error.

Error communicating with client: System.Security.SecurityException: Incorrect function.
+2  A: 

How about using LDAP queries to go against the Active Directory?

http://www.codeproject.com/KB/system/activedirquery.aspx

Raj More
I'm not sure how this is helping my case.
Ankiov Spetsnaz
I figured it out... thanks...
Ankiov Spetsnaz
A: 

Below is the code I ended up using. I had no idea about LDAP but it seems it may raise some security concerns...

public static List<string> GetUserGroups(string name)
    {
        List<string> groups = new List<string>();
        DirectorySearcher search = new DirectorySearcher("");
        int groupCount;
        int counter;
        string GroupName;
        string DataToWriteGroups;

        search.Filter = "(&(objectClass=user)(SAMAccountName=" + name + "))";
        search.PropertiesToLoad.Add("memberOf");


        SearchResult result = search.FindOne();


        groupCount = result.Properties["memberOf"].Count;

        if (groupCount > 0)
        {
            DataToWriteGroups = "Group(s) Belongs To User - " + name + "";
            for (counter = 0; counter <= groupCount - 1; counter++)
            {
                GroupName = "";
                GroupName = (result.Properties["memberOf"][counter].ToString());
                groups.Add(GroupName);
            }
        }

        return groups;
    }
Ankiov Spetsnaz