Raje
Raje

Reputation: 3333

How to perform search operation in ldap using spring

I want to search specific user details from ldap. so i have wrote down following code retrieving user details but it returns list of user object. Basically i want only person obejct not list of person objects. for retreiving i m using ldap template. How can i modify this code so that it return person object?

public void searchByFirstName(String loginId) {

        AndFilter filter = new AndFilter();
        filter.and(new EqualsFilter("objectclass", "Person"));
        filter.and(new EqualsFilter("cn", loginId));
        List list = ldapTemplate.search("", 
            filter.encode(),
            new AttributesMapper() {
                public Object mapFromAttributes(Attributes attrs) throws NamingException        {
                    return attrs.get("sn").get();
                }
            });


}

Upvotes: 2

Views: 25329

Answers (1)

Matt Ryall
Matt Ryall

Reputation: 10545

The method you're calling, ldapTemplate.search() always returns a list of matching objects. This is because it is finding all the objects that match your criteria on the LDAP server. If you're not certain that a user matching your loginId exists, you are using the correct method already. Just check the length of the list and retrieve the first item from the returned list.

To get just a single item from LDAP, you need to know the distinguished name (DN) of a user in the LDAP server. A DN is a unique identifier of an object in LDAP, and you need to know this if you're going to look up a single object specifically. Depending on your LDAP configuration, this might be something like cn=<loginId>,ou=users,dc=yourorg,dc=com.

If you can construct the DN from the loginId you have, you can use the ldapTemplate.lookup(String, AttributesMapper) method to find just a single object.

Upvotes: 5

Related Questions