spring-test-mvc junit testing Spring Security layer with LDAP

For people in hurry get the code from Github.

In continuation of my earlier blog on spring-test-mvc junit testing Spring Security layer with InMemoryDaoImpl, in this blog I will discuss how to use Spring Security’s LDAP integration.

Please follow the steps in this blog to setup spring-test-mvc and run the below test case,

mvn clean test -Dtest=com.example.springsecurity.web.controllers.Video4LdapProviderControlerTest

The dependency required integrating LDAP is as below,


In this example we used inmemory LDAP configured to work with calendar.ldif for all user/role information. In the real life, there will be a enterprise quality LDAP like Active Director configured with Spring Security. For configuring this in spring security configuration you need to add below code,

<ldap-server id="ldapServer" ldif="classpath:ldif/calendar.ldif" root="dc=jbcpcalendar,dc=com" />

The plumbing for spring-test-mvc to work with LDAP is in the class com.example.springsecurity.web.controllers.util.LdapSecurityRequestPostProcessors. The below code does the magic,

private UsernamePasswordAuthenticationToken authentication(ServletContext servletContext) {
ApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);

FilterBasedLdapUserSearch filterBasedLdapUserSearch = context.getBean(FilterBasedLdapUserSearch.class);

DirContextOperations ldapUserDetails = filterBasedLdapUserSearch.searchForUser(username);

List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(1);
authorities.add(new SimpleGrantedAuthority(ldapUserDetails.getStringAttribute("sn")));

return new UsernamePasswordAuthenticationToken(username, ldapUserDetails.getObjectAttribute("userpassword").toString(),

spring bean definition for FilterBasedLdapUserSearch is as below,

<bean id="ldapSearch">
<constructor-arg value="ou=users"/> <!-- use-search-base -->
<constructor-arg value="(uid={0})"/> <!-- user-search-filter -->
<constructor-arg ref="ldapServer"/>

I hope this blog helped. In my next blog I will be explaining how to integrate Spring Security with Method level access control.


Spring Security 3.1 by Robert Winch and Peter Mularien


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s