Spring Security, SecurityFilterChain

jkeum·2024년 5월 1일

Spring Boot

목록 보기
2/4

Spring Security

Security 설정은 애플리케이션을 보호하고, 민감한 데이터와 리소스에 대한 접근을 제어하기 위해 필수적이다.
특히 웹 애플리케이션과 같이 외부 네트워크를 통해 접근 가능한 시스템의 경우, 다양한 보안 위협으로부터 시스템을 안전하게 보호해야 한다.

Spring Security는 Java 기반의 애플리케이션에 대해 인증 및 권한 부여를 제공하는 강력하고 맞춤화 가능한 인증 및 액세스 제어 프레임워크이다.
Spring Security는 주로 다음과 같은 보안 기능을 제공한다.

  1. 인증(Authentication): 사용자가 누구인지 확인한다. 로그인 과정을 통해 사용자 신원을 확인하고, 해당 사용자가 시스템을 사용할 수 있는지 검증한다.
  2. 권한 부여(Authorization): 인증된 사용자가 수행할 수 있는 작업을 결정한다. 예를 들어, 어떤 사용자는 특정 페이지나 데이터에 접근할 수 있는 권한을 가질 수 있다.
  3. CSRF(Cross Site Request Forgery) 보호: 사용자 세션을 이용한 위조 요청을 방지한다.
  4. 세션 관리: 사용자의 세션을 보안적으로 관리하며, 세션 고정, 세션 만료 등의 처리를 담당한다.

설정 방법

  1. 의존성 추가
dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-security'
}
  1. Security Configuration 클래스 생성
    Spring Security 설정을 위한 Java 클래스를 생성하고, SecurityFilterChain 빈을 정의한다.

SecurityFilterChain

Spring Security 5.4 이후 권장하는 방식이다.
SecurityFilterChain Bean을 직접 정의하여 애플리케이션의 보안 필터 체인을 설정한다.
구성 요소의 분리를 통해 더 유연하고 명확한 보안 구성이 가능하며, 여러 개의 SecurityFilterChain Bean을 정의하여 다양한 보안 요구사항을 더 세분화하여 관리할 수 있다.

예제: SecurityFilterChain 구현

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

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
        .antMatchers("/public/**").permitAll()
        .anyRequest().authenticated()
        .and()
        .formLogin()
        .loginPage("/login").permitAll()
        .and()
        .logout().permitAll();

    return http.build();
}
profile
It's me, jkeum!

0개의 댓글