Skip to content

Tích hợp Tài khoản LDAP vào project Spring Boot

Thông tin phiên bản

  • Java 17
  • Apache Maven 3.8.6
  • Spring Boot 3.1.0-SNAPSHOT
  • Server LDAP đang hoạt động, ở đây ví dụ là ldap://ldap_server:389

Cài đặt package

Cài đặt file pom.xml như một project bình thường. Để tích hợp đăng nhập bằng LDAP ta cần cài thêm hai dependency lần lượt là Spring Boot Starter SecuritySpring Security LDAP. Trong đó, Spring Boot Starter Security sẽ cung cấp nhanh cho chúng ta các cài đặt về cấu hình bảo mật của project Spring, ví dụ như cài đặt của các chức năng đăng nhập, đăng xuất, kiểm xoát xác thực của URL. Spring Security LDAP cung cấp class ldapAuthentication để làm việc với server LDAP.

Chuẩn bị các biến môi trường của LDAP

Ta thêm vào tệp tin application.yml các tham số như sau:

ldap:
  urls: ldap://ldap_server:389/                         // URL của server LDAP
  username: cn=admin,dc=example,dc=com                  // Tài khoản Bind có quyền duyệt cây của thư mục LDAP cho mục đích tìm kiếm
  password: password                                    // Mật khẩu của tài liệu trên
  user:
    search: 
      base: dc=company,dc=example,dc=com                // Vị trí bắt đầu thực hiện duyệt cây thư mục tìm kiếm
      query: mail={0}                                   // Sử dụng field mail làm điều kiện duyệt mặc định, 
                                                        // nếu muốn sử dụng username có thể dùng uid={0} (tương tự với các field LDAP khác)
  group:
    search: 
      base: cn=groups,dc=company,dc=example,dc=com      // Vị trí nhóm mà user đăng nhập phải thuộc thì mới được truy cập
      query: member={0}                                 
logging:
  level:
    org:
      springframework:
        security: DEBUG                                  // Cấu hình để log ra các dòng debug của package spring security

Viết thêm class WebSecurity như sau

package vn.edu.siu.ailab.devicemanager.config;

import org.springframework.beans.factory.annotation.Autowired;
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.web.SecurityFilterChain;
import static org.springframework.security.config.Customizer.withDefaults;
import org.springframework.beans.factory.annotation.Value;


@Configuration
public class WebSecurityConfig {
    @Value("${ldap.urls}")
    private String ldapUrl;

    @Value("${ldap.username}")
    private String ldapBinder;

    @Value("${ldap.password}")
    private String ldapBinderPassword;

    @Value("${ldap.user.search.base}")
    private String ldapUserSearchBase;

    @Value("${ldap.user.search.query}")
    private String ldapUserSearchQuery;

    @Value("${ldap.group.search.base}")
    private String ldapGroupSearchBase;

    @Value("${ldap.group.search.query}")     
    private String ldapGroupSearchQuery;


    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        '''
        Thiết lập một số cấu hình mặc định, với 1 số path  hình ảnh, tệp tin tĩnh ta không cần yêu cầu xác thực --> để trạng thái  .permitAll()


        .formLogin(withDefaults) sẽ sử dụng giao diện đăng nhập  các path mặc định  ta không cần viết riêng Controller, hay tệp html cho chúng.

        .rememberMe(): theo tài liệu, thì ta không thể dùng chức năng rememberMe cùng với LDAP (không hỗ trợ trực tiếp)
        '''
        http.authorizeHttpRequests((authz) -> authz
                .requestMatchers("/images/**").permitAll()
                .requestMatchers("/css/**").permitAll()
                .requestMatchers("/js/**").permitAll()
                .requestMatchers("/export/**").permitAll()
                .requestMatchers("/favicon.ico").permitAll()
                .anyRequest().fullyAuthenticated()) 
                .formLogin(withDefaults());
                // .rememberMe(Customizer.withDefaults());
                // .rememberMe(cookie -> cookie.useSecureCookie(true));

        return http.build();
    }

    @Autowired
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        '''
        Ta điền các tham số vào 
        '''
        auth
                .ldapAuthentication()
                .userSearchBase(ldapUserSearchBase)
                .userSearchFilter(ldapUserSearchQuery)
                .groupSearchBase(ldapGroupSearchBase)
                .groupSearchFilter(ldapGroupSearchQuery)
                .contextSource()
                .url(ldapUrl)
                .managerDn(ldapBinder)
                .managerPassword(ldapBinderPassword);
    }
}

Hoàn tất

Nếu cấu hình chính xác, Spring Security sẽ bắt buộc ta phải đăng nhập khi truy cập website. Sau đó, các giá trị username (mail) và password sẽ được gửi đến server xác thực LDAP.