[java] 스프링 시큐리티와 LDAP 인증

스프링 시큐리티는 사용자 인증 및 권한 부여를 처리하기 위한 프레임워크로, LDAP(Lightweight Directory Access Protocol)를 사용한 인증도 지원합니다. LDAP는 네트워크 프로토콜로, 디렉토리 서비스에 접근하여 사용자 정보를 가져오고 인증을 할 수 있습니다.

설정 파일

스프링 시큐리티와 LDAP을 연동하기 위해서는 application.properties 또는 application.yml 파일에 다음과 같이 설정을 추가해야 합니다.

application.properties

spring.ldap.urls=ldap://localhost:389
spring.ldap.base=dc=mydomain,dc=com
spring.ldap.username=cn=admin,dc=mydomain,dc=com
spring.ldap.password=adminPassword
spring.security.ldap.user-dn-pattern=uid={0},ou=users
spring.security.ldap.group-search-base=ou=groups

application.yml

spring:
  ldap:
    urls: ldap://localhost:389
    base: dc=mydomain,dc=com
    username: cn=admin,dc=mydomain,dc=com
    password: adminPassword
  security:
    ldap:
      user-dn-pattern: uid={0},ou=users
      group-search-base: ou=groups

위 설정에서 ldap.urls는 LDAP 서버의 URL을, ldap.base는 베이스 DN(Distinguished Name)을, ldap.usernameldap.password는 LDAP 서버에 접속하기 위한 계정 정보를 설정합니다. ldap.user-dn-pattern은 사용자 DN 패턴, ldap.group-search-base는 그룹 검색 베이스 DN을 의미합니다.

사용자 인증

LDAP을 사용한 사용자 인증을 구현하기 위해서는 WebSecurityConfigurerAdapter를 상속받는 커스텀 설정 클래스를 작성해야 합니다. 예를 들어, 다음과 같이 SecurityConfig 클래스를 작성할 수 있습니다.

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.ldapAuthentication()
                .userDnPatterns("uid={0},ou=users")
                .groupSearchBase("ou=groups")
                .contextSource()
                .url("ldap://localhost:389/dc=mydomain,dc=com")
                .managerDn("cn=admin,dc=mydomain,dc=com")
                .managerPassword("adminPassword");
    }
}

configure() 메소드 내에서 AuthenticationManagerBuilder를 사용하여 LDAP 인증을 설정합니다. userDnPatterns()은 사용자 DN 패턴을, groupSearchBase()는 그룹 검색 베이스 DN을 설정합니다. contextSource()는 LDAP 서버의 정보를 설정하고, managerDn()managerPassword()는 LDAP 서버에 접속하기 위한 계정 정보를 설정합니다.

사용자 권한 부여

LDAP 인증 후에 사용자에게 권한을 부여하기 위해서는 @EnableGlobalMethodSecurity 애노테이션을 사용하고, WebSecurityConfigurerAdapter를 상속받는 커스텀 설정 클래스에서 @EnableGlobalMethodSecurity 애노테이션을 활성화해야 합니다. 그러면 @Secured, @PreAuthorize, @PostAuthorize 등의 애노테이션을 사용하여 메소드에 대한 접근 제어를 할 수 있습니다.

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    // ...

}

위 코드에서 @EnableGlobalMethodSecurity 애노테이션의 securedEnabledprePostEnabled 속성은 각각 @Secured@PreAuthorize, @PostAuthorize 애노테이션을 활성화합니다.

마무리

이러한 방식으로 스프링 시큐리티와 LDAP을 연동하여 사용자 인증과 권한 부여를 처리할 수 있습니다. LDAP을 사용하면 기존에 LDAP 서버에 저장된 사용자 정보를 활용하여 간단하게 인증과 권한 관리를 할 수 있습니다.

참고 자료