Skip to content

Conversation

@move-hoon
Copy link
Member

@move-hoon move-hoon commented Jul 15, 2025

🔗 관련 이슈

📘 작업 유형

  • ✨ Feature (기능 추가)
  • 🐞 Bugfix (버그 수정)
  • 🔧 Refactor (코드 리팩토링)
  • ⚙️ Chore (환경 설정)
  • 📝 Docs (문서 작성 및 수정)
  • ✅ Test (기능 테스트)
  • 🎨 style (코드 스타일 수정)

📙 작업 내역

변경 사항

  • Spring Security의 Authentication 객체에 저장되는 Principal의 타입을 기존 String에서 UUID로 변경했습니다.

문제 상황

  • 기존에는 JWT의 sub 클레임(String)이 그대로 Authentication 객체의 Principal로 사용되었습니다.
  • 이로 인해 컨트롤러에서 @AuthenticationPrincipal userId: UUID로 받으려고 하면, Spring은 String 타입의 principal을 UUID 타입으로 자동 변환하려고 시도하는 과정에서 변환해 실패하게 되었습니다.
  • 결국 null을 메서드 파라미터로 전달하게 되고 non-null 파라미터(userId: UUID)에 null이 전달되면서 NullPointerException이 발생했습니다.

해결 방법

  • jwtAuthenticationConverter의 Bean의 구현을 변경했습니다.
  • 기존의 setPrincipalClaimName()을 사용하는 대신, Converter<Jwt, AbstractAuthenticationToken>을 직접 구현했습니다.
  • 새로운 컨버터는 JWT의 sub 클레임 값을 UUID.fromString()을 통해 UUID 객체로 변환합니다.
  • 변환된 UUID 객체를 Principal로 사용하는 UsernamePasswordAuthenticationToken을 생성하여 반환하도록 수정했습니다.

🧪 테스트 내역

  • 브라우저/기기에서 동작 확인
  • 엣지 케이스 테스트 완료
  • 기존 기능 영향 없음

🎨 스크린샷 또는 시연 영상 (선택)

기능 미리보기 기능 미리보기
기능 설명 기능 설명

✅ PR 체크리스트

  • 커밋 메시지가 명확합니다
  • PR 제목이 컨벤션에 맞습니다
  • 관련 이슈 번호를 작성했습니다
  • 기능이 정상적으로 작동합니다
  • 불필요한 코드를 제거했습니다

💬 추가 설명 or 리뷰 포인트 (선택)

  • ..

Summary by CodeRabbit

  • 리팩터링
    • JWT 인증 변환 로직이 개선되어, 토큰에서 역할 정보를 보다 명확하게 추출하고 인증 처리가 더욱 안전하게 변경되었습니다.
    • 사용자 정보가 UUID 형식으로 처리되어 인증 신뢰성이 향상되었습니다.

@coderabbitai
Copy link

coderabbitai bot commented Jul 15, 2025

📝 Walkthrough

"""

Walkthrough

JwtConfig의 jwtAuthenticationConverter 메서드가 JwtAuthenticationConverter에서 커스텀 Converter<Jwt, AbstractAuthenticationToken>로 변경되었습니다. JWT의 sub 클레임을 UUID로 변환하여 principal로 사용하며, roles 클레임에서 권한을 추출하도록 JwtGrantedAuthoritiesConverter를 활용합니다. SecurityConfig에서는 jwtAuthenticationConverter 타입이 구체 클래스에서 인터페이스 타입으로 변경되었습니다.

Changes

파일/경로 변경 요약
gateway/src/main/kotlin/org/yapp/gateway/config/JwtConfig.kt jwtAuthenticationConverter를 커스텀 Converter로 리팩토링. sub 클레임을 UUID로 변환해 principal로 사용, roles에서 권한 추출. 메서드 반환 타입 및 내부 구현 변경.
gateway/src/main/kotlin/org/yapp/gateway/security/SecurityConfig.kt SecurityConfig 생성자 파라미터 jwtAuthenticationConverter 타입을 JwtAuthenticationConverter에서 Converter<Jwt, out AbstractAuthenticationToken>로 변경. 관련 import 수정.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Gateway (JwtConfig)
    participant Spring Security

    Client->>Gateway (JwtConfig): JWT 포함 요청
    Gateway (JwtConfig)->>Gateway (JwtConfig): jwtAuthenticationConverter 호출
    Gateway (JwtConfig)->>Gateway (JwtConfig): JWT에서 sub 추출 및 UUID 변환
    Gateway (JwtConfig)->>Gateway (JwtConfig): roles에서 권한 추출
    Gateway (JwtConfig)->>Spring Security: UsernamePasswordAuthenticationToken 생성 및 반환
    Spring Security-->>Client: 인증된 principal(UUID) 전달
Loading

Assessment against linked issues

Objective Addressed Explanation
AuthenticationPrincipal 타입 불일치 문제 해결 (#43)

Assessment against linked issues: Out-of-scope changes

(해당 변경사항에서 범위를 벗어난 변경사항은 발견되지 않았습니다.)
"""


📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 67e4f31 and 29adac6.

📒 Files selected for processing (1)
  • gateway/src/main/kotlin/org/yapp/gateway/security/SecurityConfig.kt (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: build-validation
🔇 Additional comments (2)
gateway/src/main/kotlin/org/yapp/gateway/security/SecurityConfig.kt (2)

8-10: 새로운 converter 인터페이스를 위한 적절한 import 추가

JWT 인증 컨버터를 인터페이스 타입으로 변경하기 위해 필요한 import 구문들이 올바르게 추가되었습니다.


19-19: 생성자 매개변수 타입의 인터페이스 변경이 적절함

JwtAuthenticationConverter 구체 클래스에서 Converter<Jwt, out AbstractAuthenticationToken> 인터페이스로 변경하여 더 유연한 의존성 주입을 가능하게 합니다. out 키워드를 통한 공변성(covariance) 사용도 올바르게 적용되었습니다.

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between cb9d02f and 67e4f31.

📒 Files selected for processing (1)
  • gateway/src/main/kotlin/org/yapp/gateway/config/JwtConfig.kt (3 hunks)
🔇 Additional comments (5)
gateway/src/main/kotlin/org/yapp/gateway/config/JwtConfig.kt (5)

11-13: 새로운 임포트들이 적절하게 추가되었습니다.

커스텀 Converter 구현을 위해 필요한 클래스들이 올바르게 임포트되었습니다.

Also applies to: 16-16, 18-18


29-29: 권한 접두어 제거를 위한 상수가 적절합니다.

NO_AUTHORITY_PREFIX 상수는 Spring Security의 기본 SCOPE_ 접두어를 제거하기 위한 명확한 의도를 나타냅니다.


72-79: 문서가 새로운 구현에 맞게 정확히 업데이트되었습니다.

메서드 문서가 새로운 커스텀 Converter 구현과 UUID 변환 로직을 정확히 설명하고 있습니다.


81-81: 메서드 시그니처 변경이 적절합니다.

JwtAuthenticationConverter에서 Converter<Jwt, out AbstractAuthenticationToken>로의 변경은 더 명시적이고 타입 안전한 접근 방식을 제공합니다.


82-84: JwtGrantedAuthoritiesConverter 설정이 올바릅니다.

roles 클레임에서 권한을 추출하고 접두어를 제거하는 설정이 적절하게 구성되었습니다.

Copy link
Member

@minwoo1999 minwoo1999 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@sonarqubecloud
Copy link

@move-hoon move-hoon merged commit 00bd424 into develop Jul 15, 2025
4 checks passed
move-hoon added a commit that referenced this pull request Jul 15, 2025
* [BOOK-143] fix: gateway - sub 클레임을 UUID 타입으로 변환하여 인증 객체의 principal로 설정하도록 수정

* [BOOK-143] fix: gateway - SecurityConfig에서 의존성 타입 일치하도록 수정
move-hoon added a commit that referenced this pull request Jul 17, 2025
* [BOOK-140] chore: apis - 패키지 이동

* [BOOK-140] refactor: apis - vo가 아닌 dto를 반화하도록 변경

* [BOOK-140] chore: apis - 개행 삭제

* [BOOK-140] chore: apis - 필요없는 명세 삭제

* [BOOK-140] feat: apis - 애플리케이션 레이어에 사용될 DTO 정의

* [BOOK-140] feat: domain - 도메인 전용 예외 클래스 구현

* [BOOK-140] refactor: domain - 역할 부여 여부에 따라 정적 팩토리 메서드 분리

* [BOOK-140] chore: apis - 패키지 이동

* [BOOK-140] chore: apis - 패키지 이동

* [BOOK-140] refactor: apis - 정적팩토리 메서드 인자로 vo를 받도록 변경

* [BOOK-140] refactor: apis - 컨트롤러에서 usecase로 갈때 dto를 받도록 변경

* [BOOK-140] refactor: apis - valid 로직 도입

* [BOOK-140] refactor: domain - 인증 로직에 사용되는 vo 구현

* [BOOK-140] refactor: domain, infra - 도메인 서비스에서 해당하는 vo를 리턴하도록 변경

* [BOOK-140] chore: infra - 새로운 메서드 추가

* [BOOK-140] refactor: apis - 인증 로직을 클린 아키텍처에 맞게 리팩토링

* [BOOK-140] chore: apis - dto 필드 검증 NotBlank로 변경

* [BOOK-140] chore: apis - 가시성을 위한 개행 추가

* [BOOK-140] refactor: apis, domain - 코드리뷰 반영

* [BOOK-140] refactor: apis, domain, infra - 코드리뷰 반영

* [BOOK-140] refactor: domain - UuidGenerator 유틸 클래스로 아이디 생성 방식 변경

* fix: sub 클레임 값을 UUID로 변환해 Authentication 객체의 principal로 설정하도록 수정 (#44)

* [BOOK-143] fix: gateway - sub 클레임을 UUID 타입으로 변환하여 인증 객체의 principal로 설정하도록 수정

* [BOOK-143] fix: gateway - SecurityConfig에서 의존성 타입 일치하도록 수정

* [BOOK-140] refactor: domain, infra - jpa 메서드 재정의

* [BOOK-140] feat: domain - 리프레쉬 토큰 관련 도메인 에러 클래스 생성

* [BOOK-140] chore: domain, apis - 메서드 네이밍 변경

* [BOOK-140] chore: domain - 필요 없는 중괄호 제거

* [BOOK-140] feat: doamin, infra - RefreshToken 도메인에 Value Class 적용 및 생성자 검증 추가

- RefreshToken 내 id, token, userId를 각각 Value Class(Id, Token, UserId)로 분리
- Value Class 내 newInstance 정적 팩토리 메서드 구현 및 검증 로직 추가

* [BOOK-140] feat: apis - 비즈니스 로직에 사용될 요청 및 응답 dto 구현

* [BOOK-140] refactor: domain - 무조건 true인 검증 제거

* [BOOK-140] refactor: requestDTO를 받도록 변경

* [BOOK-140] refactor: apis - redis 관련 인증도메인 리팩토링

* [BOOK-140] refactor: apis, infra - 값 기반 비교를 위해 객체들을 VO(Value Object)로 리팩토링

- ID, EMAIL, PROVIDERID는 동일한 값을 가지면 같은 객체임

* [BOOK-140] refactor: infra - this 추가

* [BOOK-140] refactor: apis, domain - vo 매핑으로 인한 변동사항 반영

* [BOOK-140] refactor: domain, infra - 값 기반 비교를 위해 객체들을 VO(Value Object)로 리팩토링

* [BOOK-140] refactor: apis, domain - 값 객체 매핑으로 인한 변동사항 반영

* [BOOK-140] feat: domain - 책 관련 도메인 예외 클래스 생성

* [BOOK-140] feat: domain - 책 관련 도메인 예외 클래스 생성

* [BOOK-140] refactor: domain, infra - 생성된 도메인 예외를 이용해 로직 리팩토링

* [BOOK-140] chore: apis, domain - vo 이름 구체화

* [BOOK-140] chore: infra - 패키지 변경

* [BOOK-140] refactor: domain, infra - 값 기반 비교를 위해 객체들을 VO(Value Object)로 리팩토링

* [BOOK-140] refactor: domain, apis - VO 래핑으로 인한 변동사항 반영

* [BOOK-140] refactor: apis, domain, infra - 코드레빗 리뷰 반영

* [BOOK-140] refactor: apis - 코드레빗 리뷰 반영

* [BOOK-140] chore: domain - 메서드 위치 변경

* [BOOK-140] chore: apis - 가독성을 위한 개행 추가

* [BOOK-140] feat: global-utils - email, isbn 전역 validator 구현

* [BOOK-140] refactor: domain - email, isbn 전역 validator 적용
@move-hoon move-hoon deleted the BOOK-143-fix/#43 branch August 12, 2025 06:29
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BOOK-143/fix] AuthenticationPrincipal 타입 불일치 문제

3 participants