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,
<dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-ldap</artifactId> <version>3.1.0.RELEASE</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.apache.directory.server</groupId> <artifactId>apacheds-protocol-ldap</artifactId> <version>1.5.5</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.apache.directory.shared</groupId> <artifactId>shared-ldap</artifactId> <version>0.9.15</version> <scope>compile</scope> </dependency>
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(),
authorities);
}
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"/>
</bean>
I hope this blog helped. In my next blog I will be explaining how to integrate Spring Security with Method level access control.
REFERENCE
Spring Security 3.1 by Robert Winch and Peter Mularien