Contents
1️⃣ 이 필터는 언제 동작할까?2️⃣ 전체 로그인 흐름3️⃣ 내부 동작 단계별 분석① 요청 가로채기② 아이디 / 비밀번호 추출③ UsernamePasswordAuthenticationToken 생성④ AuthenticationManager에게 전달4️⃣ AuthenticationManager는 무엇을 할까?5️⃣ DaoAuthenticationProvider의 역할6️⃣ 인증 성공 시 동작7️⃣ 인증 실패 시8️⃣ 성공/실패 핸들러성공 핸들러실패 핸들러9️⃣ 세션 기반 인증일 경우🔟 JWT 기반 구조에서는?11️⃣ 필터 체인에서의 위치12️⃣ 핵심 개념 정리🔥 핵심 포인트💡 한 줄 정리Spring Security에서 “폼 로그인”을 처리하는 핵심 필터가 바로
🔐 UsernamePasswordAuthenticationFilter
이다.
로그인 요청을 가로채서
아이디/비밀번호를 검증하고 인증을 완료하는 역할을 한다.
1️⃣ 이 필터는 언제 동작할까?
기본적으로 다음 URL 요청에서 동작한다.
POST /login
Spring Security 기본 설정을 사용하면 자동으로 등록된다.
2️⃣ 전체 로그인 흐름
클라이언트 (POST /login) ↓ UsernamePasswordAuthenticationFilter ↓ AuthenticationManager ↓ AuthenticationProvider ↓ UserDetailsService ↓ DB 조회 ↓ 비밀번호 검증 ↓ 인증 성공 ↓ SecurityContext 저장
3️⃣ 내부 동작 단계별 분석
① 요청 가로채기
if (request.getMethod().equals("POST")
&& request.getRequestURI().equals("/login"))이 조건이 맞으면 필터가 동작한다.
② 아이디 / 비밀번호 추출
String username= request.getParameter("username");
String password= request.getParameter("password");👉 기본 파라미터 이름은
username, password③ UsernamePasswordAuthenticationToken 생성
Authentication authRequest = new UsernamePasswordAuthenticationToken(username, password);이 객체는 “인증 전 상태”이다.
④ AuthenticationManager에게 전달
authenticationManager.authenticate(authRequest);
이 시점부터 실제 인증 로직이 시작된다.
4️⃣ AuthenticationManager는 무엇을 할까?
AuthenticationManager는 내부적으로
여러 AuthenticationProvider 중 적절한 Provider를 선택
한다.
보통은:
DaoAuthenticationProvider
를 사용한다.
5️⃣ DaoAuthenticationProvider의 역할
- UserDetailsService 호출
- DB에서 사용자 조회
- PasswordEncoder로 비밀번호 비교
- 인증 성공 시 Authentication 객체 반환
6️⃣ 인증 성공 시 동작
SecurityContextHolder.getContext().setAuthentication(authentication);
✔ 인증 정보가 ThreadLocal에 저장됨
✔ 이후 요청 처리에서 사용자 정보 사용 가능
7️⃣ 인증 실패 시
- BadCredentialsException
- UsernameNotFoundException
발생
이 예외는
ExceptionTranslationFilter
에서 잡아서 401 응답 처리한다.
8️⃣ 성공/실패 핸들러
UsernamePasswordAuthenticationFilter는
성공/실패 시 동작을 커스터마이징할 수 있다.
성공 핸들러
AuthenticationSuccessHandler
예:
- JWT 발급
- 로그인 성공 JSON 반환
- 리다이렉트
실패 핸들러
AuthenticationFailureHandler
예:
- 로그인 실패 메시지 반환
- JSON 에러 응답
9️⃣ 세션 기반 인증일 경우
인증 성공 시:
SecurityContext → 세션에 저장
이후 요청에서는 세션에서 인증 정보를 꺼내 사용한다.
🔟 JWT 기반 구조에서는?
보통은 이 필터를 그대로 쓰지 않고
커스텀 로그인 필터를 만들어 JWT 발급 처리
한다.
예:
public class JwtLoginFilter extends UsernamePasswordAuthenticationFilter로그인 성공 시:
- JWT 생성
- 응답 헤더에 토큰 추가
11️⃣ 필터 체인에서의 위치
보통 순서:
SecurityContextHolderFilter ↓ CsrfFilter ↓ UsernamePasswordAuthenticationFilter ↓ BearerTokenAuthenticationFilter ↓ AuthorizationFilter
👉 인증 처리 담당
12️⃣ 핵심 개념 정리
개념 | 역할 |
UsernamePasswordAuthenticationFilter | 로그인 요청 처리 |
AuthenticationManager | 인증 위임 |
AuthenticationProvider | 실제 인증 수행 |
UserDetailsService | 사용자 조회 |
PasswordEncoder | 비밀번호 검증 |
SecurityContext | 인증 정보 저장소 |
🔥 핵심 포인트
✔ 로그인은 이 필터가 담당
✔ 인증은 AuthenticationManager가 담당
✔ 성공 시 SecurityContext에 저장
✔ 실패 시 401 처리
✔ JWT 구조에서는 커스터마이징 필요
💡 한 줄 정리
UsernamePasswordAuthenticationFilter는 로그인 요청을 가로채 인증을 수행하고, 인증 성공 시 SecurityContext에 사용자 정보를 저장하는 필터이다.
Share article