Getting list of groups a user belongs to from a windows service
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 u开发者_C百科se above code but it raised the following error.
Error communicating with client: System.Security.SecurityException: Incorrect function.
How about using LDAP queries to go against the Active Directory?
http://www.codeproject.com/KB/system/activedirquery.aspx
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;
}
精彩评论