Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JWT 기반 인증 전환에 따른 세션 정보 제거 및 컨트롤러 수정 #187

Open
gunny97h opened this issue Mar 13, 2025 · 1 comment
Assignees
Labels
enhancement New feature or request feature 구현 사항

Comments

@gunny97h
Copy link
Collaborator

gunny97h commented Mar 13, 2025

📄 설명

  • 배경:

    • 기존에 세션 정보를 사용하던 부분을 JWT 기반 인증으로 전환하면서, 여러 컨트롤러에서 사용자 정보를 어떻게 가져올지 고민함.
    • 예를 들어, Controller에서 session.getAttribute("user") 대신 TokenExtractor를 통해 토큰에서 사용자 정보를 추출하도록 변경함.
  • 문제점:

    • @AuthenticationPrincipal 또는 기존 세션 사용 시 사용자 정보가 누락되거나, 인증 정보가 일관되지 않아 "사용자 정보가 없습니다." 오류 발생.
    • JWT 토큰에서 추출한 이메일과 컨트롤러에서 사용하는 사용자 조회 기준(이름, 이메일 등) 간 불일치로 인해 조회 실패.

✅ 작업할 내용

  • JwtAuthenticationFilter 수정:

    • JWT 토큰에서 이메일을 추출하여 DB 조회 후 Users 엔티티를 principal로 SecurityContext에 설정하도록 구현.
  • TokenExtractor 클래스 추가:

    • HTTP 요청에서 Authorization 헤더 또는 쿠키를 통해 토큰을 추출하고, jwtUtil을 통해 이메일을 얻은 후 사용자 정보를 조회하는 공통 로직 분리.
  • 컨트롤러 수정:

    • Controller에서 session 대신 TokenExtractor를 주입받아 사용자 정보를 모델에 추가하도록 변경.
  • 템플릿 수정:

    • Thymeleaf 템플릿에서 기존 session.user를 사용하던 부분을 모델에 담은 tokenId, tokenName 등으로 대체.

🙋🏻 참고 자료

#176 #197

@gunny97h
Copy link
Collaborator Author

원래 @AuthenticationPrincipal으로 주입된 userDetails의 getUsername()이 실제 토큰에 저장된 사용자 식별자(이메일)가 아니라, CustomUserDetailsService에서 설정한 닉네임(사용자명)을 반환하기 때문에 인증에 실패.

JwtAuthenticationFilter는 JWT 토큰에서 이메일을 추출해 DB에서 사용자 정보를 조회하고, 그 이메일을 기준으로 인증 정보를 설정. 반면, CustomUserDetailsService에서는 getUsername()을 user.getUserName()으로 반환하도록 했기 때문에, @AuthenticationPrincipal으로 주입되는 값은 닉네임.

ProductService.getCurrentUser()는 이메일을 기준으로 사용자를 조회하도록 구현되어 있다면, userDetails.getUsername()으로 전달된 닉네임과 DB의 이메일 컬럼이 일치하지 않아 조회에 실패.

반면에, 수정한 코드는 HttpServletRequest에서 직접 토큰을 추출하고, jwtUtil.getUsernameFromToken(token)을 호출하여 실제 토큰에 저장된 이메일을 가져옴.

@gunny97h gunny97h added the enhancement New feature or request label Mar 13, 2025
@gunny97h gunny97h changed the title HttpSession을 JWT 토큰으로 수정 JWT 기반 인증 전환에 따른 세션 정보 제거 및 컨트롤러 수정 Mar 13, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request feature 구현 사항
Projects
None yet
Development

No branches or pull requests

2 participants