본문 바로가기
Spring/Spring Security

Spring Security 고급 설정

by 롱싱싱 2024. 11. 25.

다중 보안 설정

SecurityFilterChain @Bean을 등록해서 다중 보안 기능 구성 가능

a패턴, b패턴, c패턴에 맞춰 각 요청에 맞는 보안 기능을 설정할 수 있다.

클라이언트 요청에 맞는 보안 설정 처리

 

두개의 SecurityFilterChain을 만들면 FilterChainProxy의 SecurityFilterChains에 저장하고, 요청에 부합하는 적합한 FilterChain을 선택하여 요청을 처리한다.

@Configuration
@EnableWebSecurity
public class MultiHttpSecurityConfig {
    @Bean
    @Order(1) // @Order 를 사용하여 어떤 SecurityFilterChain 을 먼저 수행 할지 지정한다. 아래 설정보다 우선적으로 보안 기능을 수행한다
    public SecurityFilterChain apiFilterChain(HttpSecurity http) throws Exception {
        http.securityMatcher("/api/**") // HttpSecurity가 /api/로 시작하는 URL 에만 적용 된다
            	.authorizeHttpRequests(authorize -> authorize 
                .anyRequest().hasRole("ADMIN"))
            .httpBasic(withDefaults());
        return http.build();
    }
    @Bean // @Order 가 지정되지 않으면 마지막으로 간주 된다
    public SecurityFilterChain SecurityFilterChain(HttpSecurity http) throws Exception {
        http .authorizeHttpRequests(authorize -> authorize
        		.anyRequest().authenticated()) // HttpSecurity 가 /api/ 를 제외한 모든 URL 에 적용 된다
        	.formLogin(withDefaults());
        return http.build();
    }
}

 


Custom DSLs - HttpSecurity.with(AbstractHttpConfigurer)

DSL을 구성하면 필터, 핸들러, 메서드, 속성 등을 한 곳에 정의하여 처리할 수 있다.

 

AbstractHttpConfigurer <AbstractHttpConfigurer, HttpSecurityBuilder>

사용자 DSL을 구현하기 위해서 상속받는 추상클래스 -> 구현은 두 개의 메서드를 오버라이딩 한다.

  • init(B builder) - HttpSecurity의 구성 요소를 설정 및 공유하는 작업
  • configure(B builder) - 공통 클래스를 구성하거나 사용자 정의 필터를 생성하는 작업

API

HttpSecurity.with(C configurer, Customizer<C> customizer)

  • configurer는 AbstractHttpConfigurer를 상속하고 DSL을 구현한 클래스가 들어간다.
  • customizer는 DSL 구현 클래스에서 정의한 여러 API를 커스터마이징한다.
  • 동일한 클래스를 여러 번 설정하더라도 한번만 적용됨
http.with(new MyCustomDsl(), dsl -> dsl.flag(true));
// MyCustomDsl 비활성화
http.with(new MyCustomDsl(), dsl -> dsl.disabled());

 


Redis를 활용한 이중화 설정 @EnableRedisHttpSession

  • 이중화는 시스템의 부하를 분산하고, 단일실패 지점 없이 서비스를 지속적으로 제공하는 아키텍처를 구현하는 것을 목표로 함. -> 스프링 시큐리티는 이중화 환경에서 인증, 권한부여, 세션관리 등의 보안 기능 제공
  • 스프링 시큐리티는 이중화된 환경에서 세션 정보를 공유할 수 있는 메커니즘을 제공함. Redis같은 분산 캐시를 사용하여 세션 정보를 여러 서버 간 공유