스택큐힙리스트

Spring Security Filter Chain 깊게 파보기 — 인증 vs 인가 본문

개발

Spring Security Filter Chain 깊게 파보기 — 인증 vs 인가

스택큐힙리스트 2025. 7. 19. 11:15
반응형

Spring Security의 Filter Chain은 톱니바퀴처럼 맞물려 인증(Authentication) 과 인가(Authorization) 를 순차적으로 처리합니다. 톱니 하나만 빠져도 전체 보안이 흔들리기에, 각 필터가 언제·무엇을·어떻게 수행하는지 이해해야 커스텀 보안 전략을 안전하게 설계할 수 있어요.


1. Filter Chain이란?

  • Servlet Filter들의 묶음입니다. DispatcherServlet 앞에서 요청·응답을 가로채 인증 혹은 인가 로직을 실행합니다.
  • Spring Boot 3/Spring Security 6부터는 SecurityFilterChain 빈으로 설정하며, 더 이상 WebSecurityConfigurerAdapter를 사용하지 않습니다.
  • 필터는 등록 순서대로 실행되므로, 커스텀 필터 추가 시 위치를 명확히 지정해야 합니다.

2. 인증(Authentication) 영역 필터

  1. SecurityContextPersistenceFilter – 이전 요청에서 저장된 SecurityContext 복원
  2. UsernamePasswordAuthenticationFilter / BearerTokenAuthenticationFilter – (폼 로그인·JWT) 자격 증명 검사
  3. AbstractAuthenticationProcessingFilter 하위 필터들 – 소셜 로그인, X509 등 특수 인증
  4. 인증 성공 시 Authentication 객체가 SecurityContextHolder에 저장되고, 다음 단계로 이동합니다.

3. 인가(Authorization) 영역 필터

  1. ExceptionTranslationFilter – 이후 필터에서 인증·권한 예외가 터지면 401/403 응답으로 변환
  2. FilterSecurityInterceptor – URL·메서드 보안 (@PreAuthorize 등) 최종 검사
  3. 이 단계에서 권한이 없으면 403, 통과하면 실제 컨트롤러로 진입합니다.

기억할 것: “인증 필터 → 예외 처리 → 인가 필터” 흐름이 기본 골격입니다. 커스텀 권한 필터를 넣더라도 이 질서를 깨지 않도록 주의하세요.

4. 커스텀 인증/인가 필터 끼워넣기

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    return http
        .addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
        .addFilterAfter(roleHierarchyFilter(), FilterSecurityInterceptor.class)
        .authorizeHttpRequests(auth -> auth
            .requestMatchers("/admin/**").hasRole("ADMIN")
            .anyRequest().authenticated())
        .build();
}
  • addFilterBefore : 인증 영역 앞에 JWT 검증 필터 삽입.
  • addFilterAfter : 인가 영역 뒤에 roleHierarchyFilter로 추가적인 권한 검사 수행.

5. 실행 순서 확인 방법

spring:
  security:
    filter:
      debug: true

DEBUG 로그에 필터 체인 순서가 출력되므로, 예상 위치에 필터가 걸렸는지 바로 확인 가능합니다.

6. Spring Security 6에서 달라진 점

  • antMatchers() → requestMatchers() 로 변경 (람다 DSL)
  • WebSecurityCustomizer 로 정적 리소스(이미지·CSS) 예외 처리
  • 기본 제공 BearerTokenAuthenticationFilter 덕분에 JWT 사용 시 별도 필터를 줄일 수 있음

7. 베스트 프랙티스

  • 짧은 인증·긴 인가: 인증 필터는 “누구인가”만 빠르게 확인, 인가는 비즈니스 규칙에 집중합니다.
  • 필터 책임 단일화: 하나의 필터에 여러 역할을 섞지 마세요. 유지보수 악몽이 됩니다.
  • HTTPS 전제: 필터 체인 전에 네트워크 계층 보안을 우선 확보하세요.
  • 테스트 코어: MockMvc · @WithMockUser 조합으로 인증/인가 시나리오를 e2e 테스트합니다.
반응형
Comments