Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

LDAP Integration with Spring Security

Integrating LDAP (Lightweight Directory Access Protocol) with Spring Security allows you to authenticate users against an LDAP directory. This guide covers key concepts and steps for setting up LDAP authentication in your Spring Boot application, including adding dependencies, configuring LDAP settings, and securing endpoints.

Key Concepts of LDAP Integration

  • LDAP (Lightweight Directory Access Protocol): A protocol used to access and manage directory information services.
  • LDAP Authentication: Verifying user credentials against an LDAP directory.
  • Security Configuration: Configuring Spring Security to use LDAP for authentication.

Adding Dependencies

Include the Spring Security LDAP dependency in your pom.xml file:

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

Configuring LDAP Settings

Configure LDAP settings in the application.yml file:

Example: application.yml

spring:
  ldap:
    urls: ldap://localhost:8389/
    base: dc=springframework,dc=org
    username: cn=admin,dc=springframework,dc=org
    password: secret

Configuring LDAP Authentication

Configure LDAP authentication by extending WebSecurityConfigurerAdapter and overriding the configure(AuthenticationManagerBuilder auth) and configure(HttpSecurity http) methods:

Example: SecurityConfiguration.java

// SecurityConfiguration.java
package com.example.myapp.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .ldapAuthentication()
            .userDnPatterns("uid={0},ou=people")
            .groupSearchBase("ou=groups")
            .contextSource()
            .url("ldap://localhost:8389/dc=springframework,dc=org")
            .and()
            .passwordCompare()
            .passwordEncoder(passwordEncoder())
            .passwordAttribute("userPassword");
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
            .authorizeRequests()
            .antMatchers("/public/**").permitAll()
            .anyRequest().authenticated()
            .and()
            .formLogin()
            .loginPage("/login")
            .defaultSuccessUrl("/home", true)
            .failureUrl("/login?error=true")
            .and()
            .logout()
            .logoutSuccessUrl("/login?logout=true")
            .permitAll();
    }
}

Creating Login Form

Create a custom login page to handle user authentication:

Example: login.html

<!DOCTYPE html>
<html>
<head>
    <title>Login</title>
    <link rel="stylesheet" type="text/css" href="/css/styles.css" />
</head>
<body>
    <div class="swf-lsn-container">
        <h2>Login</h2>
        <form method="post" action="/login">
            <div>
                <label>Username:</label>
                <input type="text" name="username" />
            </div>
            <div>
                <label>Password:</label>
                <input type="password" name="password" />
            </div>
            <div>
                <input type="submit" value="Login" />
            </div>
        </form>
        <div class="swf-lsn-error-message">
            <#if error?string?trim != "">
                Invalid username or password.
            </#if>
            <#if logout?string?trim != "">
                You have been logged out.
            </#if>
        </div>
    </div>
</body>
</html>

Securing Endpoints

Protect specific endpoints by specifying access rules:

Example: SecurityConfiguration.java

// SecurityConfiguration.java
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable()
        .authorizeRequests()
        .antMatchers("/public/**").permitAll()
        .anyRequest().authenticated()
        .and()
        .formLogin()
        .loginPage("/login")
        .defaultSuccessUrl("/home", true)
        .failureUrl("/login?error=true")
        .and()
        .logout()
        .logoutSuccessUrl("/login?logout=true")
        .permitAll();
}

Testing LDAP Authentication

Ensure your LDAP server is running and contains the appropriate user entries. Use tools like LDAP Admin or Apache Directory Studio to manage and verify your LDAP entries.

Key Points

  • LDAP (Lightweight Directory Access Protocol): A protocol used to access and manage directory information services.
  • LDAP Authentication: Verifying user credentials against an LDAP directory.
  • Security Configuration: Configuring Spring Security to use LDAP for authentication.
  • Include the Spring Security LDAP dependency in your pom.xml file.
  • Configure LDAP settings in the application.yml file.
  • Configure LDAP authentication by extending WebSecurityConfigurerAdapter and overriding the configure(AuthenticationManagerBuilder auth) and configure(HttpSecurity http) methods.
  • Create a custom login page to handle user authentication.
  • Protect specific endpoints by specifying access rules.
  • Ensure your LDAP server is running and contains the appropriate user entries for testing LDAP authentication.

Conclusion

Integrating LDAP with Spring Security allows you to authenticate users against an LDAP directory. By understanding and configuring LDAP settings, security configuration, and authentication flows, you can ensure secure access to your application's resources. Happy coding!