Course – LSS – NPI (cat=Spring Security)
announcement - icon

If you're working on a Spring Security (and especially an OAuth) implementation, definitely have a look at the Learn Spring Security course:

>> LEARN SPRING SECURITY

1. Overview

In this quick tutorial, we will learn how to set up Spring Security LDAP.

Before we start, a note about what LDAP is – it stands for Lightweight Directory Access Protocol and it’s an open, vendor-neutral protocol for accessing directory services over a network.

Further reading:

Spring LDAP Overview

Learn how to use the Spring LDAP APIs to authenticate and search for users, as well as to create and modify users in the directory server.

Guide to Spring Data LDAP

Learn how to use Spring Data with LDAP.

Spring Data with Spring Security

See how to integrate Spring Data with Spring Security.

2. Maven Dependency

First, let take a look at maven dependencies we need:

<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-ldap</artifactId>
</dependency>

<dependency>
    <groupId>org.apache.directory.server</groupId>
    <artifactId>apacheds-server-jndi</artifactId>
    <version>1.5.5</version>
</dependency>

Note: We used ApacheDS as our LDAP server which is an extensible and embeddable directory server.

3. Java Configuration

Next, let’s discuss our Spring Security Java configuration:

public class SecurityConfig {

    @Bean
    ApacheDSContainer ldapContainer() throws Exception {
        return new ApacheDSContainer("dc=baeldung,dc=com", "classpath:users.ldif");
    }

    @Bean
    LdapAuthoritiesPopulator authorities(BaseLdapPathContextSource contextSource) {
        String groupSearchBase = "ou=groups";
        DefaultLdapAuthoritiesPopulator authorities = new DefaultLdapAuthoritiesPopulator
           (contextSource, groupSearchBase);
        authorities.setGroupSearchFilter("(member={0})");
        return authorities;
    }

    @Bean
    AuthenticationManager authenticationManager(BaseLdapPathContextSource contextSource, 
        LdapAuthoritiesPopulator authorities) {
        LdapBindAuthenticationManagerFactory factory = new LdapBindAuthenticationManagerFactory
           (contextSource);
        factory.setUserSearchBase("ou=people");
        factory.setUserSearchFilter("(uid={0})");
        return factory.createAuthenticationManager();
    }
 }

This is of course only the LDAP relevant part of the config – the full Java configuration can be found here.

4. XML Configuration

Now, let’s take a look at corresponding XML configuration:

<authentication-manager>
    <ldap-authentication-provider
      user-search-base="ou=people"
      user-search-filter="(uid={0})"
      group-search-base="ou=groups"
      group-search-filter="(member={0})">
    </ldap-authentication-provider>
</authentication-manager>
   
<ldap-server root="dc=baeldung,dc=com" ldif="users.ldif"/>

Again, this is just part of the configuration – the part that is relevant to LDAP; the full XML config can be found here.

5. LDAP Data Interchange Format

LDAP data can be represented using the LDAP Data Interchange Format (LDIF) – here’s an example of our user data:

dn: ou=groups,dc=baeldung,dc=com
objectclass: top
objectclass: organizationalUnit
ou: groups

dn: ou=people,dc=baeldung,dc=com
objectclass: top
objectclass: organizationalUnit
ou: people

dn: uid=baeldung,ou=people,dc=baeldung,dc=com
objectclass: top
objectclass: person
objectclass: organizationalPerson
objectclass: inetOrgPerson
cn: Jim Beam
sn: Beam
uid: baeldung
userPassword: password

dn: cn=admin,ou=groups,dc=baeldung,dc=com
objectclass: top
objectclass: groupOfNames
cn: admin
member: uid=baeldung,ou=people,dc=baeldung,dc=com

dn: cn=user,ou=groups,dc=baeldung,dc=com
objectclass: top
objectclass: groupOfNames
cn: user
member: uid=baeldung,ou=people,dc=baeldung,dc=com

6. Using Spring Boot

When working on a Spring Boot project, we can also use Spring Boot Starter Data Ldap dependency that will automatically instrument LdapContextSource and LdapTemplate for us. 

To enable autoconfiguration, we need to ensure that we have the spring-boot-starter-data-ldap Starter or spring-ldap-core defined as a dependency in our pom.xml:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-ldap</artifactId>
</dependency>

To connect to LDAP, we need to provide the connection settings in the application.properties:

spring.ldap.url=ldap://localhost:18889
spring.ldap.base=dc=example,dc=com
spring.ldap.username=uid=admin,ou=system
spring.ldap.password=secret

More details about Spring Data LDAP autoconfiguration can be found in the official documentation. Spring Boot brings in LdapAutoConfiguration which takes care of instrumentation of LdapTemplate which can then be injected into the required service class:

@Autowired
private LdapTemplate ldapTemplate;

7. The Application

Finally, here is our simple application:

@Controller
public class MyController {

    @RequestMapping("/secure")
    public String secure(Map<String, Object> model, Principal principal) {
        model.put("title", "SECURE AREA");
        model.put("message", "Only Authorized Users Can See This Page");
        return "home";
    }
}

8. Conclusion

In this quick guide to Spring Security with LDAP, we learned how to provision a basic system with LDIF and configure the security of that system.

The full implementation of this tutorial can be found in the GitHub project – this is an Eclipse-based project, so it should be easy to import and run as it is.

Course – LSS (cat=Security/Spring Security)

I just announced the new Learn Spring Security course, including the full material focused on the new OAuth2 stack in Spring Security:

>> CHECK OUT THE COURSE
res – Security (video) (cat=Security/Spring Security)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.