active-directoryldapactive-directory-group

LDAP Query to List All Groups User is a Member of?


Given a username, how would I go about writing an LDAP query that will return all groups that the user is a member of?


Solution

  • Are you on .NET 3.5 ??

    If so, check out this excellent MSDN article Managing Directory Security Principals in the .NET Framework 3.5 which shows the new feature for user and groups management in .NET 3.5.

    In this case, you need a principal context (e.g. your domain):

    PrincipalContext domainContext = 
       new PrincipalContext(ContextType.Domain, "YourDomain");
    

    and then you can pretty easily find the user:

    UserPrincipal user = UserPrincipal.FindByIdentity(principalContext, "username");
    

    and the "UserPrincipal" object has a method called "GetAuthorizationGroups" which returns all groups the user is a member of:

    PrincipalSearchResult<Principal> results = user.GetAuthorizationGroups();
    
    // display the names of the groups to which the
    // user belongs
    
    foreach (Principal result in results)
    {
        Console.WriteLine("name: {0}", result.Name);
    }
    

    Pretty easy, huh?

    It's a lot more work in .NET before 3.5, or in "straight" LDAP from some other language (PHP, Delphi etc.).

    Marc