Integration of Spring Security with Spring LDAP Authentication in Spring Boot

Here’s an end-to-end example of integrating Spring Security with Spring LDAP for authentication in a Spring Boot  application.


1. Set Up Local LDAP Server

To install and run an LDAP server locally, you can use Apache Directory Server or OpenLDAP. Here, I'll use Apache Directory Server (Apache DS) because it's easy to set up and works well with Spring Boot.

1.1. Install Apache Directory Server

  1. Download Apache Directory Server from the official site.

    • Choose the latest version based on your operating system.
  2. Install Apache Directory Server:

    • Extract the downloaded ZIP or tar.gz file to a directory of your choice.
    • Open a terminal or command prompt and navigate to the directory where you extracted the server.
  3. Start Apache Directory Server:

    • Run the following command to start the LDAP server:
    bin/apacheds.sh start

    For Windows, use bin/apacheds.bat start.

  4. Access the Apache Directory Studio (optional) for easier interaction with your LDAP server:

    • Download Apache Directory Studio (which provides a GUI to manage your LDAP data).
    • Once downloaded, open it and connect to your LDAP server (usually, localhost on port 10389 for the default installation).

    Default credentials to connect:

    • Username: uid=admin,ou=system
    • Password: secret

1.2. Configure LDAP Directory

You can use the Apache Directory Studio or any other LDAP browser to create an entry in your LDAP server, such as a user. For example:

  • DN (Distinguished Name): uid=testuser,ou=users,dc=example,dc=com
  • Attributes: uid, cn, sn, userPassword

You can also use LDIF (LDAP Data Interchange Format) to create the entries. Here's an example of an LDIF file to add a user:

dn: uid=testuser,ou=users,dc=example,dc=com
objectClass: inetOrgPerson
uid: testuser
cn: Test User
sn: User
userPassword: secret

2. Integrating Local LDAP with Spring Boot

Once the LDAP server is running, we can now configure Spring Boot to connect to the LDAP server.

2.1. Create Spring Boot Project

If you haven’t already created your Spring Boot project, use Spring Initializr and add the following dependencies:

  • Spring Web
  • Spring Security
  • Spring LDAP
  • Thymeleaf

You can also add Spring Boot DevTools for faster development and Spring Data LDAP for easier integration with Spring.

2.2. Add Configuration to application.properties

Configure the connection details to the local LDAP server in src/main/resources/application.properties:

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

2.3. Create Spring Security Configuration

Next, create a configuration class to set up Spring Security to use LDAP authentication.

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.ldap.core.support.LdapContextSource;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.ldap.LdapUserDetailsService;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.authentication.AuthenticationManagerBuilder;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    // Define the LdapContextSource to connect to the LDAP server
    @Bean
    public LdapContextSource contextSource() {
        LdapContextSource contextSource = new LdapContextSource();
        contextSource.setUrl("ldap://localhost:10389");
        contextSource.setBase("dc=example,dc=com");
        contextSource.setUserDn("uid=admin,ou=system");
        contextSource.setPassword("secret");
        return contextSource;
    }

    // Define LdapUserDetailsService
    @Bean
    public UserDetailsService ldapUserDetailsService() {
        LdapUserDetailsService service = new LdapUserDetailsService();
        service.setLdapContextSource(contextSource());
        return service;
    }

    // Define HTTP security configuration
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
            .antMatchers("/login").permitAll()  // Allow login page to be accessed by all
            .anyRequest().authenticated()  // Other requests need authentication
            .and()
            .formLogin()
            .loginPage("/login")
            .permitAll()
            .and()
            .logout()
            .permitAll();
        return http.build();
    }
}

2.4. Create a Simple Controller

Create a simple controller with endpoints for login and home page.

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class MainController {

    @GetMapping("/login")
    public String login() {
        return "login";
    }

    @GetMapping("/home")
    public String home() {
        return "home";
    }
}

2.5. Create login.html and home.html for Views

Create basic Thymeleaf templates in src/main/resources/templates/ for login and home.

login.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login</title>
</head>
<body>
    <h2>Login Page</h2>
    <form action="/login" method="post">
        <label for="username">Username:</label><br>
        <input type="text" id="username" name="username" required><br><br>
        <label for="password">Password:</label><br>
        <input type="password" id="password" name="password" required><br><br>
        <input type="submit" value="Login">
    </form>
</body>
</html>

home.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Home</title>
</head>
<body>
    <h2>Welcome to the Home Page</h2>
    <p>You're logged in!</p>
</body>
</html>

2.6. Run the Application

Run your Spring Boot application using the following command:

mvn spring-boot:run

Access the application at http://localhost:8080/. You can log in using the LDAP credentials you created earlier (for example, uid=testuser,ou=users,dc=example,dc=com with the password secret).

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete