Java – ldap search in java – finding all groups with a specific user in it

javajndildap

Given the below ldap structure (more or less)

C=NO
-o=mydomain
--cn=groups
---cn=group1
----uid=bob,cn=users,o=mydomain,C=NO
---cn=group2
----uid=bob,cn=users,o=mydomain,C=NO
----uid=odd,cn=users,o=mydomain,C=NO
--cn=users
---uid=bob,cn=Robert,sn=Johnsen
---uid=odd,cn=Odd,sn=Olsen

I use the following url= ldap://server:port/o=mydomain,C=NO

Then I can retrieve basically the entire tree with a search somewhat like this:

NamingEnumeration results = ctx.search("cn=groups", "cn=*", constraints);

where constraints is

constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);

However, I'd like to receive only the groups with a specific user in it. I've tried lots and lots of variants like

        NamingEnumeration results = ctx.search("cn=groups"
                , "(&(uid={0},cn=users,o=fund,C=NO)(cn=*))"
                        , new Object[] {"odd"}
                        , constraints);

but I get only empty results. All or nothing it seems… I suspect the problem is that cn=* and uid=odd are on different levels in the tree, eg. uid=is an attribute, but cn=* is a node one level above?

How would I go about to complete this search in a more effective manner than just retrieving everything and parse it clientside?

Best Answer

Your LDAP structure looks strange.

what is the class of objects like cn=group1 ? is this "organizationalUnit" or "group"?

In usual Directories users are created under objects based on the "organizationalUnits" class, and for administrative needs they are grouped in an attribute called "member" of objects of the class "group".

In this case the LDAP filter would be like :

(&(objectClass=group)(member=uid={0},cn=users,o=fund,C=NO))

With the architecture you discribe you may have a look to a feature called ExtensibleMatch which seems to be correctly explained in this wiki article .