Question

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();
Was it helpful?

Solution

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

OTHER TIPS

If you're on .NET 3.5 and up, you should check out the System.DirectoryServices.AccountManagement (S.DS.AM) namespace. Read all about it here:

Basically, you can define a domain context and easily find users and/or groups in AD:

    // define context for current domain
    using(PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
    {
        // find  user 
        UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "YourNameHere");

        if (user != null)
        {
            // get groups the user is a member of
            var groups = current.GetGroups();

            // iterate over all those groups
            foreach(var group in groups)
            {
                // fetch the SID for each group
                var sid = group.Sid;
            }
        }
    }   

The new S.DS.AM makes it really easy to play around with users and groups in AD!

Have a look at his article: Retrieving user SID using DirectoryEntry and DirectorySearcher

This gives you a full working example for retrieving the SID.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top