Spring Security 설정 가이드

@EnableWebSecurity 어노테이션

@EnableWebSecurity 어노테이션은 WebSecurity 모드를 활성화하는 역할을 담당합니다. 이는 Spring Security에서 웹 보안을 설정하기 위해 반드시 필요한 어노테이션입니다.

Spring Boot를 사용하지 않는 일반 Spring Web MVC 프로젝트에서는 해당 어노테이션을 명시적으로 추가해야 합니다. 반면, Spring Boot 기반의 Spring Web MVC 애플리케이션에서는 WebSecurityEnableAutoConfiguration 클래스를 통해 자동 설정되므로 별도로 선언할 필요가 없습니다.

참고 문서: https://www.baeldung.com/spring-deprecated-websecurityconfigureradapter

인증 전략 구현: UserDetailsService와 PasswordEncoder

사용자 정보를 관리하기 위해 UserDetailsService 구현체와 PasswordEncoder를 Spring Bean으로 등록하면 됩니다. 이렇게 하면 Spring Security가 자동으로 이를 인식하여 AuthenticationManager로 구성합니다.

이전 버전과 달리 별도로 AuthenticationManagerBuilder를 통해 수동 설정할 필요가 없어졌습니다.

보안 설정의 변화

Spring Security 5.7 버전 이전에는 WebSecurityConfigurerAdapter를 상속받아 보안 설정을 구성했습니다. 그러나 5.7 이후로는 해당 클래스가 deprecated 되었고, 컴포넌트 기반의 설정 방식이 권장됩니다.

현재는 SecurityFilterChain을 통해 HttpSecurity를 구성하고, WebSecurityCustomizer를 통해 WebSecurity를 커스터마이징하는 방식이 표준입니다.

HTTP 보안 설정: SecurityFilterChain

SecurityFilterChain Bean을 정의하여 요청 인가 및 인증 규칙을 설정할 수 있습니다. 다음은 모든 요청에 대해 인증을 요구하고 폼 로그인을 활성화하는 기본 설정입니다.

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class SecurityConfig {
    
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests(auth -> auth
                .anyRequest().authenticated()
            )
            .formLogin(form -> form.loginPage("/login"));
        
        return http.build();
    }
}

웹 보안 설정: WebSecurityCustomizer

특정 경로를 보안 필터 체인에서 제외하거나 디버그 모드를 활성화할 때 사용합니다. 정적资源(이미지, 스크립트, 스타일시트 등)이나 공개 API 경로를 필터링 대상에서 제외할 수 있습니다.

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public WebSecurityCustomizer webSecurityCustomizer() {
        boolean enableDebug = true;
        
        return web -> web
            .debug(enableDebug)
            .ignoring()
            .antMatchers("/assets/**", "/images/**", "/scripts/**")
            .antMatchers("/api/public/**");
    }

}

태그: spring-boot spring-security authentication authorization web-security

6월 24일 00:55에 게시됨