Tutorial :Getting list of groups a user belongs to from a windows service



Question:

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.  


Solution:1

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

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


Solution:2

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;      }  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »