Kkrap/개발하면서 공부하게 된 것들

[Spring boot] JWT 로그인 요청 검증 방법

재윤 2025. 8. 8. 13:49
반응형

SecurityConfig

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .cors(cors -> cors.configurationSource(corsConfigurationSource())) // CORS 설정 추가
                .csrf(csrf -> csrf.disable()) //
                .authorizeHttpRequests(authorize -> authorize
                                .requestMatchers("/auth/**", "/profile/**").permitAll() // 정적 리소스 허용
                                .anyRequest().authenticated()
                )
                .exceptionHandling(ex -> ex
                        .authenticationEntryPoint(customAuthenticationEntryPoint) // 등록
                )
                .addFilterBefore(new JwtAuthenticationFilter(jwtUtil, usersService),
                        UsernamePasswordAuthenticationFilter.class);

        return http.build();
    }
  • 사용자는 /auth에 관련된 api에 로그인을 요청을 보낸다 이때 filter를 타긴 하지만 token 검증을 하는 JwtAuthenticationFilter를 타지 않는다.
  • 다른 api들은 무조건 JwtAuthenticationFilter를 탄다.

좀 더 분석해보자

로그인 시(/auth/login, /auth/kakao 같은 경로)

  1. 클라이언트 → 카카오 로그인 토큰 전달
  2. 컨트롤러/서비스(validateUser)에서 카카오 사용자 정보 조회
  3. DB 조회 & 신규 유저 생성 여부 판단
  4. jwtUtil.generateAccessToken / generateRefreshToken 호출 → 토큰 발급
  5. 응답 바디나 쿠키로 클라이언트에 전달
  6. 이 과정에서는 UsernamePasswordAuthenticationFilter가 전혀 개입하지 않음

다른 API 호출 시

  1. 클라이언트 → Authorization: Bearer <accessToken> 헤더 포함
  2. JwtAuthenticationFilter가 체인에서 토큰 검증 (jwtUtil.validateToken)
  3. 검증 성공 → new UsernamePasswordAuthenticationToken(principal, null, authorities) 생성 후 SecurityContextHolder에 저장
  4. 이후 Security 인가 단계에서 인증된 사용자로 처리
  5. 여기서 나오는 UsernamePasswordAuthenticationToken은 폼 로그인 필터가 만든 게 아니라, JwtAuthenticationFilter가 직접 만든 Authentication 객체

즉 처음 accesstoken을 UsernamePasswordAuthenticationToken에 넣어주면 다른 Api 요청에서도 인증이 완료된 사용자로 Security는 판단

반응형

'Kkrap > 개발하면서 공부하게 된 것들' 카테고리의 다른 글

CI/CD란?  (1) 2025.08.25
[Spring boot] JWT Accesstoken 및 Refresh 검사 흐름?  (3) 2025.08.08
[Spring boot] JWT 관리 코드 분석  (2) 2025.08.08
JWT란?  (5) 2025.08.03
커서 기반 페이지네이션이란?  (1) 2025.07.30