Saturday, 1 August 2015

C#: Get nested group membership for AD user

In .NET C#, we can get the list of AD user group memberships using two methods. In first method, we can get nested groups from the constructed attribute TokenGroups, it requires the dll reference System.DirectoryServices (It is available from .NET Framework 2.0). In second method, we can find and list all the nested groups using UserPrincipal class, it requires the dll reference System.DirectoryServices.AccountManagement (It is available from .NET Framework 3.5).

Get nested group memberships for AD user using TokenGroups:

The following C# function returns all the nested groups for the given user. Since TokenGroups is the constructed attribute, we need to use RefreshCache in user's DirectoryEntry to get attribute value.
//----using System.DirectoryServices;
private static List<string> GetNestedGroupMembershipsByTokenGroup(string userDN)
{
    List<string> nestedGroups=new List<string>();

    DirectoryEntry userEnrty = new DirectoryEntry("LDAP://" + userDN);
    // Use RefreshCach to get the constructed attribute tokenGroups.
    userEnrty.RefreshCache(new string[] { "tokenGroups" });

    foreach (byte[] sid in userEnrty.Properties["tokenGroups"])
    {
        string groupSID = new SecurityIdentifier(sid, 0).ToString();
        DirectoryEntry grpuEnrty = new DirectoryEntry("LDAP://<SID=" + groupSID + ">");
        nestedGroups.Add(grpuEnrty.Properties["samAccountName"][0].ToString());
    }

    return nestedGroups;
}

Get nested group memberships for AD user using UserPrincipal:

The following C# function returns the nested group memberships for the given user using UserPrincipal class.
//----using System.DirectoryServices.AccountManagement;
private static List<string> GetNestedGroupMembershipsByUserPrincipal(string username)
{
    List<string> nestedGroups = new List<string>();

    UserPrincipal userPrincipal = UserPrincipal.FindByIdentity(
                        new PrincipalContext(ContextType.Domain), username);
    foreach (Principal group in userPrincipal.GetGroups())
    {
        nestedGroups.Add(group.SamAccountName);
    }

    return nestedGroups;
}

Advertisements
Advertisements

No comments:

Post a Comment