How to get SID of a group once i get groups of a user in Active Directory?

phanish m picture phanish m · Jul 3, 2012 · Viewed 12.4k times · Source

I am using DirectorySearcher to get groups of a User in ActiveDirectory.

My Question is how to get SID associated with each group once i get user groups using "memberOf"?

I am working in .NETFramework 2.0 Environment.

DirectoryEntry entry = new DirectoryEntry(string.Format("LDAP://{0}", sUserDomain));
DirectorySearcher mySearcher = new DirectorySearcher(entry);
mySearcher.Filter = string.Format("(&(objectClass=user) (cn= {0}))", ui.DisplayName.ToString());
mySearcher.PropertiesToLoad.Add("memberOf");
SearchResult searchresult = mySearcher.FindOne();

Answer

Harvey Kwok picture Harvey Kwok · Jul 4, 2012

There is no way to do it in one single LDAP search because memberOf returns a distinguish name. You have to do another bind to get the objectSid attribute from the group object. Here is the code.

DirectoryEntry entry = new DirectoryEntry(string.Format("LDAP://{0}", sUserDomain));
DirectorySearcher mySearcher = new DirectorySearcher(entry);
mySearcher.Filter = string.Format("(&(objectClass=user) (cn= {0}))", ui.DisplayName.ToString());
mySearcher.PropertiesToLoad.Add("memberOf");
SearchResult searchresult = mySearcher.FindOne();

foreach (string dn in searchresult.Properties["memberOf"])
{
    DirectoryEntry group = new DirectoryEntry(string.Format("LDAP://{0}/{1}", sUserDomain, dn));
    SecurityIdentifier sid = new SecurityIdentifier(group.Properties["objectSid"][0] as byte[], 0);
    Console.Out.WriteLine(sid.Value);
}