본문 바로가기

3.구현/Java or Kotlin

[Java] spring boot에서 spring security 사용하기 3 - LDAP

들어가기

LDAP(Lightweight Directory Access Protocol)은 중앙 집중 사용자 정보 저장소와 인증 서비스 형태로 자주 사용된다. 대부분의 예제가 내장 ldap 서버를 사용했지만 실제 외부 서버 연동할 때 다시 어떻게 해야할지 모르는 상황이 된다. 그래서 이글에서는 외부 오픈 ldap 서버를 사용한 ldap 인증을 사용했다. 혹시, ldap을 잘모른다면 먼저 간단하게 공부하는 것을 추천한다.[4]

작성자: http://ospace.tistory.com/ (ospace114@empal.com)

환경 구성

기본 환경 구성을 시작해보자.

Dependency 설정

Pom.xml 파일에 LDAP 인증을 위해 spring security 외에 추가적인 dependency가 필요하다.

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

환경설정

application.properties 파일에 연결할 ldap 서버를 설정한다. 사용할 LDAP 테스트 서버는 forumsys.com에서 제공하는 서버이다.[2]

spring.ldap.urls = ldap://ldap.forumsys.com:389/
spring.ldap.base = dc=example,dc=com
spring.ldap.username = cn=read-only-admin,dc=example,dc=com
spring.ldap.password = password

LDAP에 대해서는 별도로 공부가 필요하다.

HTML 파일

다음으로 접속할 웹 페이지 하나를 추가해보자. 제대로 동작하는지 확인하기 위한 목적이다.

“/resources/static/index.html” 파일을 생성한다.

<html lang="en">
<body>
    <h1>Hello world!</h1>
    <a href="/logout">Logout</a>
</body>
</html>

Spring Security 설정

이제 본격적?으로 설정해보자. 생각보다 별거 없다.

@Configuration
@EnableWebSecurity
public class SecurityConfig {
    @Autowired
    public void configure(AuthenticationManagerBuilder builder, BaseLdapPathContextSource contextSource) throws Exception {
        builder
                .ldapAuthentication()
                .userDnPatterns("uid={0}")
                .contextSource(contextSource);
    }

    @Bean
    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests(req->req
                        .anyRequest().fullyAuthenticated()
                )
                .formLogin(Customizer.withDefaults());

        return http.build();
    }
}

정말 별거 없다. 물론 ldapAuthentication()에서 ldap 서버 정보를 입력할 수 있지만 설정으로 별도로 분리했다. BaseLdapPathContextSource으로 설정된 ContextSource 객체를 받아서 입력한다. 그리고 securityFilterChain()에서 모든 요청에 대해 인증이 되도록 설정한다.

테스트

기본 설정으로 구성했다면 http://localhost:8080 으로 접속하면 된다. 아래와 같이 인증 안된 상태이기 때문에 로그인 화면이 표시된다.

Fig 1. 로그인 화면

모든 계정에 기본 패스워드가 “password”로 되어 있기 때문에 임의 계정을 선택해서 로그인하면 된다. 제대로 인증되었다면 아래와 같은 페이지가 표시된다.

Fig 2. 메인 화면

Github

프로젝트 경로: https://github.com/ospace/spring-works/tree/main/spring-security-03

결론

많은 시행착오 끝에 원하는 결과를 얻을 수 있었다. 정리해보니 생각보다 너무 쉬워서 허무하기도 하다. ldap 브라우저는 Apache Directory Studio를 추천한다. 지금 사용했던 ldap 테스트 서버는 언제 닫히질 모르겠네요. 해당 서버는 단순 읽기만 가능하기 때문에 ldap 서버에 CRDU를 할 경우는 별도 서버를 구성해서 사용해야합니다. 물론 내장 ldap 서버를 구성해서 사용하는게 간편하다.

부족한 글이지만 여러분에게 도움이 되었으면 하네요. 모두 즐거운 코딩생활 되세요. ^^ ospace.

참고

[1] LDAP Authentication, https://docs.spring.io/spring-security/reference/servlet/authentication/passwords/ldap.html

[2] Online LDAP Test Sever, https://www.forumsys.com/2022/05/10/online-ldap-test-server/

[3] Authenticating a User with LDAP, https://spring.io/guides/gs/authenticating-ldap

[4] LDAP 이란, https://ldap.or.kr/ldap-이란/

[5] LDAP for Rocket Scientists, www.zytrax.com/books/ldap/

반응형