Search code examples
springldapopenldapspring-ldap

ldap find object by group member


I am using spring ldaptemplate. I am trying to member out roles from my group. Schema is as follows .

ou=roles,cn=admin
member cn=key1,ou=Keys
member cn=key2,ou=keys

ou=roles,cn=user
member cn=key3,ou=Keys
member cn=key2,ou=keys

I want to find out roles whose member cn=key2 .

My query is

ldapTemplate.search(
            query().where("objectclass").is("groupOfNames").and("ou")
                        .is(roles).and("cn").is("key2"), PERSON_CONTEXT_MAPPER);

where I am missing?Is their any alternate using ldaptemplate.


Solution

  • An LDAP search filters on attribute values, so your search needs to match on the member attribute:

    ldapTemplate.search(
        query().
            where("objectclass").is("groupOfNames").
            and("member").is("cn=key2,ou=keys"), PERSON_CONTEXT_MAPPER);
    

    Note that in the case above you need to supply the full DN of the user you're looking for. The filter will match all groupOfName entries where the specified DN is present as a member.

    Also, please note that you should never build distinguished name strings manually, since escaping rules etc are tricky. For building the user DN to be included in the member attribute match, have a look at LdapNameBuilder.