tags:

views:

7955

answers:

1

I want to write an LDAP query which tests whether a user (sAMAccountName) is a member of a particular group. Is it possible to do that so that I get either 0 or 1 result records?

I guess I can get all groups for the user and test each one for a match but I was wondering if I could pack it into one LDAP expression.

Any ideas?

Thanks

+5  A: 

You should be able to create a query with this filter here:

(&(objectcategory=user)(sAMAccountName=yourUserName)
  (memberof=CN=YourGroup,OU=Users,DC=YourDomain,DC=com))

and when you run that against your LDAP server, if you get a result, your user "yourUserName" is indeed a member of the group "CN=YourGroup,OU=Users,DC=YourDomain,DC=com

Try and see if this works!

If you use C# / VB.Net and System.DirectoryServices, this snippet should do the trick:

    DirectoryEntry rootEntry = new DirectoryEntry("LDAP://dc=yourcompany,dc=com");

    DirectorySearcher srch = new DirectorySearcher(rootEntry);
    srch.SearchScope = SearchScope.Subtree;

    srch.Filter = "(&(objectcategory=user)(sAMAccountName=yourusername)(memberof=CN=yourgroup,OU=yourOU,DC=yourcompany,DC=com))";

    SearchResultCollection res = srch.FindAll();

    if(res == null || res.Count <= 0)
    {
        Console.WriteLine("This user is *NOT* member of that group");
    }
    else
    {
        Console.WriteLine("This user is INDEED a member of that group");
    }

Word of caution: this will only test for immediate group memberships, and it will not test for membership in what is called the "primary group" (usually "cn=Users") in your domain. It does not handle nested memberships, e.g. User A is member of Group A which is member of Group B - that fact that User A is really a member of Group B as well doesn't get reflected here.

Marc

marc_s
Tried, but still not working for me. Should it be 'OU=Users' or 'OU=Groups' in the memberOf clause?
paul
What's the DN of your group name? It depends on what you really want to check for......
marc_s
You need to put in the actual real values in your case - my stuff is just demo placeholders!
marc_s
paul
On a whim I removed the single quotes after memberof and I now get a result! Thanks
paul