ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel
  • »
  • Technology»
  • Computers & Software»
  • Computer Science & Programming

Spring Simple LDAP authentication example using ldaptemplate

Updated on January 27, 2012

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="">
		<property name="url" ref="ldapServer" />
		<property name="base" value="" />
		<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.


    0 of 8192 characters used
    Post Comment

    • profile image

      Anonymous 6 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 for more details.Also I suggest using spring security framework for ldap authentication.