Spring Simple LDAP authentication example using ldaptemplate

Spring framework provides different ways to authenticating a user against a LDAP either through spring LDAP templates or through spring security. Here I explained how to authenticate the user using the spring ldap template.

spring LDAP template is used for simple authentication of the user. Spring ldap template need a contextSource to make the connection to the LDAP server which can be injected in the spring.xml

Configuration in the spring.xml

	<bean id="contextSource" class="org.springframework.ldap.core.support.LdapContextSource">
		<property name="url" ref="ldapServer" />
		<property name="base" value="o=myCompany.com" />
		<property name="userDn" ref="ldapUser" />
		<property name="password" ref="ldapPassword" />

	<bean id="ldapTemplate" class="org.springframework.ldap.core.simple.SimpleLdapTemplate">
		<constructor-arg ref="contextSource" />
	<bean id="myEmployeeDao" class="com.myCompany.ldap.dao.MyEmployeeDao">
		<property name="ldapTemplate" ref="ldapTemplate" />
	<jee:jndi-lookup id="ldapServer" jndi-name="config/ldapServer" resource-ref="true" />
	<jee:jndi-lookup id="ldapUser" jndi-name="config/ldapUserName" resource-ref="true" />
	<jee:jndi-lookup id="ldapPassword" jndi-name="config/ldapPassword" resource-ref="true" />

The ldapServer,ldapUser and ldapPassword are references to JNDI values. The properties in the context source can also be given directly.

The context source would make the connection to the ldap server using the userDn and password provided.

When a user with a user name as "tester" is trying to login to the system,the user will be authenticated using the ldap template as below.

public boolean login(String username, String password){
  AndFilter filter = new AndFilter();
  filter.and(new EqualsFilter("ou", "testingDept")).and(new EqualsFilter("cn", username));
  return ldapTemplate.authenticate(DistinguishedName.EMPTY_PATH, filter.toString(), password);

The filter class is used to create the filtering criteria for the ldap.

Comments 1 comment

Anonymous 5 years ago

One major point to note while authenticating against active directory is that it doesn't 't handle referral and you will get PartialResultException: Unprocessed Continuation Reference(s), to avoid this problem setIgnorePartialResultException(true), check http://javarevisited.blogspot.com/2011/11/ldap-aut... for more details.Also I suggest using spring security framework for ldap authentication.

    Sign in or sign up and post using a HubPages Network account.

    0 of 8192 characters used
    Post Comment

    No HTML is allowed in comments, but URLs will be hyperlinked. Comments are not for promoting your articles or other sites.

    Click to Rate This Article