이론을 넘어 코드로!
JWT 커스텀 필터 완벽 구현하기
안녕하세요, code-resting입니다. 어제는 JWT의 구조와 인증 흐름을 살펴보았는데요. 오늘은 실제 Spring Boot 프로젝트에 JwtAuthenticationFilter를 등록하고, 보안 필터 체인(Security Filter Chain)을 구성하는 실전 코드를 파헤쳐 보겠습니다.
1. Spring Security Filter Chain의 이해
Spring Security는 여러 개의 필터가 연결된 '체인' 형태로 동작합니다. 우리의 목표는 UsernamePasswordAuthenticationFilter 앞에 우리가 만든 JWT 검증 필터를 끼워 넣는 것입니다.
2. JwtAuthenticationFilter 구현
OncePerRequestFilter를 상속받아 모든 요청마다 토큰을 검사하도록 구현합니다. 헤더에서 토큰을 추출하고 유효성을 검증한 뒤, SecurityContextHolder에 인증 정보를 저장하는 것이 핵심입니다.
public class JwtAuthenticationFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, ...) {
// 1. 헤더에서 Authorization: Bearer {Token} 추출
String token = resolveToken(request);
// 2. 토큰 유효성 검증
if (token != null && jwtTokenProvider.validateToken(token)) {
// 3. 인증 객체 생성 및 Context 저장
Authentication auth = jwtTokenProvider.getAuthentication(token);
SecurityContextHolder.getContext().setAuthentication(auth);
}
filterChain.doFilter(request, response);
}
}
3. SecurityConfig 설정 (Spring Boot 3.x 스타일)
최신 스프링 시큐리티에서는 lambda 형식의 설정을 권장합니다. 세션을 사용하지 않으므로 STATELESS 설정을 반드시 추가해야 합니다.
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.csrf(AbstractHttpConfigurer::disable) // 토큰 방식이므로 disable
.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/login", "/api/join").permitAll()
.anyRequest().authenticated()
)
// 필터 순서 지정
.addFilterBefore(new JwtAuthenticationFilter(jwtProvider),
UsernamePasswordAuthenticationFilter.class);
return http.build();
}
4. 예외 처리: AuthenticationEntryPoint
인증되지 않은 사용자가 보호된 리소스에 접근할 때, 401 Unauthorized 에러를 세련되게 반환하는 핸들러를 등록합니다.
필터에서 발생하는 예외는 @ControllerAdvice로 잡을 수 없습니다. 따라서 반드시 AuthenticationEntryPoint를 별도로 구현하여 SecurityConfig에 등록해줘야 합니다.
💡 실무 적용 팁
JWT 로그인을 구현할 때 많은 분이 실수하는 것이 '토큰 만료 처리'입니다. 프론트엔드와 협의하여 만료 시 특정 에러 코드를 내려주고, 클라이언트가 이를 감지해 Refresh Token으로 갱신 로직을 타게 만드는 것이 완성도 높은 보안 설계의 핵심입니다.
'스프링 > SpringSecurity' 카테고리의 다른 글
| [실전] Spring Security + OAuth2 소셜 로그인(구글, 카카오) & JWT 연동 마스터 (0) | 2026.03.18 |
|---|---|
| 로그인의 정석: Spring Security + JWT 무상태(Stateless) 인증 구조 완벽 이해 (0) | 2026.03.16 |
| JWT + SpringSecurity (0) | 2021.03.20 |
| SPRING SECURITY (0) | 2021.02.09 |
댓글