Ad

Thursday, April 28, 2011

Spring LDAP

Here is a simple example on how you would retrieve a user's ldap credentials using spring ldap:
http://blog.javachap.com/index.php/ldap-user-management-with-spring-ldap/

Configure a spring ldap context source:

<bean id="contextSource" class="org.springframework.security.ldap.DefaultSpringSecurityContextSource">
<constructor-arg value="${ldap.url}"/>
<property name="base" value="${ldap.base}"/>
<property name="userDn" value="${ldap.username}"/>
<property name="password" value="${ldap.password}"/>
</bean>

<bean id="ldapTemplate" class="org.springframework.ldap.core.LdapTemplate">
<constructor-arg ref="contextSource"/>
</bean>


You can then use the ldap template to query the ldap directory and map the relevant fields:

public User getUser(String userId) {
AndFilter filter = new AndFilter();
filter.and(new EqualsFilter("objectclass", "person")).and(
new EqualsFilter("uid", userId));
List<User> users = ldapTemplate.search(DistinguishedName.EMPTY_PATH,
filter.encode(), new AttributesMapper() {
public Object mapFromAttributes(Attributes attributes) throws NamingException {

User user = new User();
user.setEmail(attributes.get("mail").toString());

return user;
}
});

if (users.isEmpty()) {
return null;
}
return users.get(0);
}

No comments: