Home > Articles > Programming > Windows Programming

  • Print
  • + Share This
This chapter is from the book

Determining User Group Membership in Active Directory and ADAM

We often need to know a user’s group membership, especially when building applications that require role-based security. There are many cases when we cannot simply rely on Windows to do this expansion for us, and we need an LDAP-based approach instead. Unfortunately, many samples that attempt to show how to do this miss important details or make key mistakes that can lead to compromised security in our applications. We attempt to right these wrongs and show some proven techniques that have been effective for us.

Two linked multivalued attributes, called member and memberOf, control group membership. The group object always holds the member attribute. The memberOf attribute is a calculated back link held on the group member object itself. As such, group membership is always managed from the group object side (the forward link) of the relationship and the back link is updated by the system automatically. That is, we can read the memberOf attribute, but we cannot modify it directly. This multivalued attribute contains the user’s direct group membership, with one exception: It does not contain what is called the primary group. This group receives special treatment, and we cover how to read it in the next chapter.

When we say that the memberOf attribute contains the user’s direct membership, we mean that while we can view groups that directly contain the user object, we cannot view any group membership that is derived from the nesting of group memberships. We will have to use either a recursive technique or the tokenGroups attribute to expand a user’s membership fully.

It turns out that using the tokenGroups attribute is typically what we are after. This attribute holds a security identifier (SID) for each security group (including the aforementioned primary group) for which the user is a member, including nested group membership. Recursive solutions can often be a little messy. As such, the only advantage that the recursive technique holds is that it will expand group membership in distribution lists, while the tokenGroups attribute contains only security group membership.

We will cover three techniques for reading group membership using the tokenGroups attribute. The first technique will use an LDAP search to find each SID in the tokenGroups attribute, and the second technique will use the DsCrackNames API to convert them in a single batch. The third technique will be a .NET 2.0-only solution using the new IdentityReference-based classes.

Our ultimate goal will be to convert the tokenGroups attribute into a collection of human-readable group names. A typical example of this is to build a GenericPrincipal object and fill it with roles for a custom ASP.NET Forms authentication mechanism.

Retrieving the User’s Token Groups

Regardless of the technique we choose to decode the tokenGroups attribute, we must first retrieve it. Since this is a constructed attribute, we must use the RefreshCache technique shown in Chapter 3 to first load the attribute into the property cache in a DirectoryEntry object. This is one of the few attributes that requires a Base search scope with DirectorySearcher, so we will generally choose to use a DirectoryEntry instance for this work instead:

//user is a DirectoryEntry
  new string[] {"tokenGroups"}

//now the attribute will be available
int count = user.Properties["tokenGroups"].Count;

  "Found {0} Token Groups",

Technique #1: Using an LDAP Search

The big upshot to this approach is that this technique is pretty fast and we don’t have to worry about using any P/Invoke code that can be intimidating to less-experienced developers. We simply iterate through the returned attribute and build a large LDAP filter that represents each security group. Once we build the filter, we can easily search the domain for the groups and return each one. Listing 10.19 shows how we can accomplish this.

Listing 10.19: Retrieving Token Groups with an LDAP Search

StringBuilder sb = new StringBuilder();

//we are building an ’|’ clause

foreach (byte[] sid in user.Properties["tokenGroups"])
  //append each member into the filter
    "(objectSid={0})", BuildFilterOctetString(sid));

//end our initial filter

DirectoryEntry searchRoot = new DirectoryEntry(

using (searchRoot)
  //we now have our filter, we can just search for the groups
  DirectorySearcher ds = new DirectorySearcher(
    sb.ToString() //our filter

  using (SearchResultCollection src = ds.FindAll())
    foreach (SearchResult sr in src)
      //Here is each group now...

private string BuildFilterOctetString(byte[] bytes)
  //see listing 4.2 for the complete code

We rely on the helper method called BuildFilterOctetString from Listing 4.2 in Chapter 4 to format the binary SID correctly into a format we can use for our filter. This technique is fairly simple and relatively elegant. It is a great solution when we want to get more information about each group than just the name. The downside is that we don’t directly have access to the DOMAIN\GroupName format from SearchResult. That would require string parsing, an additional search to find the NetBIOS name of the domain from the configuration partition, or a call to DsCrackNames to convert the name appropriately into our chosen format. Since DOMAIN\GroupName happens to be one of the most widely used formats, this tends to be its major drawback.

Notice that we use the sAMAccountName attribute to identify the group. This is important, as the sAMAccountName is used for security purposes and is unique in the domain. We often see samples that parse the DN to retrieve the group’s CN. However, a CN can be duplicated in different containers in the same domain, so we can accidentally introduce security flaws by assuming it is unique. Always use a unique identifier intended for security purposes when making security decisions!

Technique #2: Using DsCrackNames

A more advanced technique exists that relies on the DsCrackNames API and forgoes searching the directory completely. The basic premise is that we will convert all of the byte-format SIDs into their string-readable Security Descriptor Description Language (SDDL)–format equivalents and pass an entire array of them into the DsCrackNames API, which can convert them into another format of our choosing (DN, NT Account format, etc.).

For .NET version 1.1, this requires using P/Invoke in order to convert the SID into SDDL format. It also involves wrapping the DsCrackNames API. Getting everything set up requires a bit of work, but it works well once it is done.

We have included all of the P/Invoke code and wrappers needed to use this functionality in the sample code included on this book’s web site. For reference purposes, Listing 10.20 includes some of the important bits.

Listing 10.20: Using DsCrackNames to Convert TokenGroups

//convert to array of string SIDs
int size = this.Properties["tokenGroups"].Count;
PropertyValueCollection pvc = this.Properties["tokenGroups"];

string[] sids = new string[size];

for (int i=0; i < size; i++)
  sids[i] = AdUtils.ConvertSidToSidString((byte[])pvc[i]);

//we want to pass in the SID format and retrieve
//the NT Format names. This utility class is
//included in our web site library samples
//groupNames contains all the converted groups now
string[] groupNames = AdUtils.DsCrackNamesWrapper(

Listing 10.20 uses two wrapper classes that help us convert a binary SID to the SDDL-format SID, and wraps our call to DsCrackNames. We are omitting this wrapper code because it would take several pages to present and it contains mostly P/Invoke declarations. We are also going to gloss over how we came to get the RPC handle necessary for DsCrackNames, for similar reasons. We wish we could dive into this code, as it is interesting, but it just takes too much book space and is irrelevant for this discussion. As usual, the complete listing is available on the book’s web site. We should also note that developers more familiar with the IADsNameTranslate ADSI interface are free to substitute this method for DsCrackNames. They are actually one and the same.

For version 2.0, we no longer need to use P/Invoke for converting the SID, as we can do this using the SecurityIdentifier class. However, if we are already using version 2.0, then we should use technique #3 instead.

Technique #3: Using the SidIdentifier and IdentityReference Classes

This last technique uses the SidIdentifier and IdentityReference classes to convert between any of the IdentityReference-derived formats. These classes are available only in .NET 2.0. As demonstrated in Listing 10.21, this is the cleanest and simplest solution out of the three. As long as we are after only one of the IdentityReference formats (of which the widely used NTAccount format is one), we are in pretty good shape.

Listing 10.21: Using SidIdentifier and IdentityReference

//we use the collection in order to 
//batch the request for translation
IdentityReferenceCollection irc 
  = ExpandTokenGroups(user).Translate(typeof(NTAccount));

foreach (NTAccount account in irc)

//Sample Helper Function
private IdentityReferenceCollection ExpandTokenGroups(
  DirectoryEntry user)
  user.RefreshCache(new string[]{"tokenGroups"});
  IdentityReferenceCollection irc = 
    new IdentityReferenceCollection();

  foreach (byte[] sidBytes in user.Properties["tokenGroups"])
    irc.Add(new SecurityIdentifier(sidBytes, 0));
  return irc;

Each technique we presented has its own advantages and disadvantages. Depending on what information we require, we might choose one or more of the options. For instance, it is entirely plausible that we will want more information about each group, yet we also will want the group’s NT format name. In this case, we might combine techniques #1 and #2 or #1 and #3.

Retrieving tokenGroups from ADAM

So far, the techniques we have described have applied to Active Directory. However, we may wish to expand an ADAM user’s group membership as well. Additionally, if we are using ADAM in a pass-through authentication scenario where we are authenticating Windows users, we might like to know both their Windows and ADAM group memberships.

It turns out that ADAM also supports the tokenGroups attribute for ADAM users and bind proxy objects. We can use the same techniques we just described for them as well. The only caveat is that we cannot refer to ADAM groups by their sAMAccountName, as they do not have one. We also cannot use any Windows-based techniques for resolving SIDs into names, such as techniques #2 and #3 that we just described. We must use an LDAP search, as shown with technique #1.

ADAM has an additional trick up its sleeve, though. The RootDSE object supports the tokenGroups attribute as well and will provide both the Windows and ADAM group SIDs for the currently bound user. This is especially helpful with pass-through authentication, as there is no actual object representing the user in ADAM in this scenario. What object would we query to read the tokenGroups attribute? The code looks approximately like this:

DirectoryEntry entry = new DirectoryEntry(

entry.RefreshCache(new string[] {"tokenGroups"});

We should instantly notice that something is strange here. We are using the GC provider with ADAM and specifying a port of 389 (our ADAM instance’s LDAP port in this case). What gives?

For some reason, the LDAP provider in ADSI cannot retrieve constructed attributes off of the RootDSE object, but the GC provider can. We also do not specify the RootDSE object name in the ADsPath in this case. We are uncertain of the reason, but we know this works.

At this point, the list of group SIDs we read from the tokenGroups attribute may contain both Windows and ADAM SIDs, so we may need to do two passes to resolve them into friendly names. However, we can still use techniques #1, #2, and #3 to do this.

  • + Share This
  • 🔖 Save To Your Account