19. BearerTokenAuthenticationFilter

김해준's avatar
Feb 26, 2026
19. BearerTokenAuthenticationFilter
JWT 기반 인증을 사용할 때 핵심이 되는 필터가 바로
🔐 BearerTokenAuthenticationFilter
이다.
이 필터는 요청 헤더에 포함된
Authorization: Bearer {토큰}
을 검사하여 인증을 수행한다.

1️⃣ 언제 동작할까?

클라이언트가 요청을 보낼 때:
GET/api/userAuthorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
이 헤더가 존재하면 필터가 동작한다.

2️⃣ 전체 요청 흐름

클라이언트 ↓BearerTokenAuthenticationFilter ↓ 토큰 추출 ↓AuthenticationManager ↓JwtAuthenticationProvider ↓JWT 검증 ↓Authentication 객체 생성 ↓SecurityContext 저장 ↓Controller 실행

3️⃣ 내부 동작 단계별 분석

① Authorization 헤더 확인

String header = request.getHeader("Authorization");

② "Bearer " 접두어 검사

Authorization: Bearer {token}
  • "Bearer "로 시작하는지 확인
  • 아니면 필터 통과 (인증 시도 안 함)

③ 토큰 추출

String token = header.substring(7);

④ Authentication 객체 생성

BearerTokenAuthenticationToken authenticationToken
이 객체는 “검증 전 상태”이다.

⑤ AuthenticationManager로 전달

authenticationManager.authenticate(authenticationToken);

4️⃣ JwtAuthenticationProvider의 역할

AuthenticationManager는 내부적으로
JwtAuthenticationProvider
에게 위임한다.
이 Provider는:
  1. JWT 서명 검증
  1. 만료 시간(exp) 검사
  1. 토큰 위변조 확인
  1. Claim 정보 추출
  1. 권한 정보 생성
을 수행한다.

5️⃣ 인증 성공 시

SecurityContextHolder.getContext().setAuthentication(authentication);
✔ 사용자 정보 저장
✔ 이후 요청에서 인증된 사용자로 인식

6️⃣ 인증 실패 시

예외 발생:
  • InvalidBearerTokenException
  • JwtException
  • AuthenticationException
→ ExceptionTranslationFilter에서 401 처리

7️⃣ UsernamePasswordAuthenticationFilter와 차이

구분
UsernamePasswordAuthenticationFilter
BearerTokenAuthenticationFilter
인증 방식
ID/PW 로그인
토큰 인증
동작 시점
로그인 시
모든 요청
세션 사용
보통 사용
Stateless 구조
토큰 필요
X
O

8️⃣ 필터 체인에서의 위치

보통 순서:
SecurityContextHolderFilter ↓ CsrfFilter ↓ UsernamePasswordAuthenticationFilter ↓ BearerTokenAuthenticationFilter ↓ AuthorizationFilter
👉 로그인 이후 요청 인증 담당

9️⃣ JWT 기반 구조의 전체 흐름

1️⃣ 로그인

POST /login
→ UsernamePasswordAuthenticationFilter 실행
→ JWT 발급

2️⃣ 이후 요청

GET /api/userAuthorization: Bearer {jwt}
→ BearerTokenAuthenticationFilter 실행
→ JWT 검증
→ 인증 성공

🔟 왜 이 필터가 필요한가?

JWT는 세션을 사용하지 않는다.
즉:
  • 서버는 로그인 상태를 저장하지 않는다
  • 매 요청마다 토큰을 검증해야 한다
이 작업을 담당하는 필터가 바로
BearerTokenAuthenticationFilter
이다.

1️⃣1️⃣ Stateless 구조에서의 핵심

JWT 구조에서는 보통:
sessionCreationPolicy(SessionCreationPolicy.STATELESS)
로 설정한다.
이 경우:
✔ 세션 저장 안 함
✔ 매 요청마다 JWT 검증
✔ 확장성 좋음 (분산 서버 환경)

1️⃣2️⃣ 핵심 포인트

✔ Authorization 헤더에서 Bearer 토큰 추출
✔ JWT 서명 및 만료 검증
✔ SecurityContext에 저장
✔ 세션 없이 인증 처리

🔥 한 줄 정리

BearerTokenAuthenticationFilter는 요청 헤더의 Bearer 토큰(JWT)을 검증하여 매 요청마다 인증을 수행하는 필터이다.
 
Share article