Skip to content

Conversation

@nayonsoso
Copy link
Collaborator

@nayonsoso nayonsoso commented Jul 26, 2025

관련 이슈

작업 내용

프론트 개발자님이 멘토/멘티 탭 구현할 때 더 편하다 하셔서 추가합니다 🏃‍♀️

  • AccessToken 생성자 파라미터 변경
  • TokenProvider에 claim 으로 토큰 만드는 함수 생성
  • 토큰 재발급 시에도 role을 포함하여 응답하도록 수정

특이 사항

디스코드에 말씀드린 "auth 패키지 대변경🧹" 관점에서 추가설명하자면,

이번에 AccessToken 생성 방법 변경으로 '토큰 재발급 함수'에 아래의 변경이 있었습니다.

/* 전 */
AccessToken accessToken = authTokenProvider.toAccessToken(token);

/* 후 */
Subject subject = authTokenProvider.parseSubject(token);
long siteUserId = Long.parseLong(subject.value());
SiteUser siteUser = siteUserRepository.findById(siteUserId)
       .orElseThrow(() -> new CustomException(USER_NOT_FOUND));
AccessToken accessToken = authTokenProvider.generateAccessToken(subject, siteUser.getRole());

이 변경의 문제

  • AccessToken 생성 로직이 여러 곳에 흩어져 있어, 방식을 바꿀 때 각 위치를 모두 수정해야 했다.
  • 기존의 authTokenProvider.toAccessToken(token)도 더 이상 사용할 수 없게 되어 아예 삭제했다.

방안

  • AccessToken 생성 책임을 한 곳에만 두기
  • 일관된 변환 함수 생성 : “문자열 → Token 객체”로 바꿔주는 단일 메서드를 구현하면, 생성 방식이 바뀌어도 영향 x

리뷰 요구사항 (선택)

@coderabbitai
Copy link

coderabbitai bot commented Jul 26, 2025

"""

Walkthrough

  1. 인증 토큰 발급 및 재발급 로직 개선
    • AuthController의 reissueToken 메서드가 @Authorizeduser로 주입된 siteUserId 파라미터를 추가로 받도록 변경되어, AuthService의 reissue 호출 시 사용자 ID를 명시적으로 전달합니다.
  2. AccessToken에 역할(Role) 정보 추가
    • AccessToken 레코드에 Role 필드가 새롭게 추가되어, 토큰 생성 시 사용자 역할 정보가 포함됩니다.
  3. AuthService의 주요 메서드 시그니처 및 내부 로직 변경
    • reissue, signOut 메서드가 siteUserId를 인자로 받도록 시그니처가 변경되고, 사용자 정보를 직접 조회하여 역할 기반으로 AccessToken을 생성하도록 수정되었습니다.
  4. AuthTokenProvider의 토큰 생성 방식 확장
    • generateAccessToken 메서드가 Role 파라미터를 추가로 받아, JWT 내에 role 클레임을 포함해 토큰을 생성하며, 기존의 역할 없는 토큰 생성 메서드는 제거되었습니다.
  5. TokenProvider 및 JwtTokenProvider의 커스텀 클레임 지원 추가
    • TokenProvider 인터페이스에 클레임을 포함하는 오버로드 generateToken 메서드가 추가되고, JwtTokenProvider 구현체도 커스텀 클레임을 받아 JWT를 생성하는 메서드를 새로 도입했습니다.
  6. 서비스 및 테스트 코드 일관성 확보
    • SignInService, AuthServiceTest, AuthTokenProviderTest, JwtTokenProviderTest, TokenBlackListServiceTest 등에서 변경된 토큰 생성 방식과 시그니처에 맞춰 테스트 및 서비스 코드가 일괄적으로 수정되고, 역할 정보가 포함된 토큰 생성이 반영되었습니다.
  7. 테스트 코드 리팩토링
    • 중복되는 테스트 객체 생성 코드를 @beforeeach 메서드로 통합하고, 역할 정보 포함 및 새로운 메서드 시그니처에 맞춰 테스트가 리팩토링되어 가독성과 유지보수성이 향상되었습니다.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20분

  • 여러 서비스 및 컨트롤러, 토큰 관련 클래스와 테스트 코드에 걸쳐 역할(Role) 기반 토큰 발급 및 검증 로직이 일괄적으로 적용되었습니다.
  • 메서드 시그니처 변경, 커스텀 클레임 추가, 테스트 리팩토링 등 다양한 중간 난이도의 변경이 포함되어 있어 집중적인 검토가 필요합니다.

Suggested reviewers

  • Gyuhyeok99
  • wibaek
  • whqtker
    """

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1c861d0 and e48e8e7.

📒 Files selected for processing (11)
  • src/main/java/com/example/solidconnection/auth/controller/AuthController.java (1 hunks)
  • src/main/java/com/example/solidconnection/auth/service/AccessToken.java (1 hunks)
  • src/main/java/com/example/solidconnection/auth/service/AuthService.java (2 hunks)
  • src/main/java/com/example/solidconnection/auth/service/AuthTokenProvider.java (2 hunks)
  • src/main/java/com/example/solidconnection/auth/service/SignInService.java (1 hunks)
  • src/main/java/com/example/solidconnection/auth/service/TokenProvider.java (1 hunks)
  • src/main/java/com/example/solidconnection/auth/token/JwtTokenProvider.java (2 hunks)
  • src/test/java/com/example/solidconnection/auth/service/AuthServiceTest.java (5 hunks)
  • src/test/java/com/example/solidconnection/auth/service/AuthTokenProviderTest.java (5 hunks)
  • src/test/java/com/example/solidconnection/auth/service/JwtTokenProviderTest.java (1 hunks)
  • src/test/java/com/example/solidconnection/auth/service/TokenBlackListServiceTest.java (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (11)
  • src/test/java/com/example/solidconnection/auth/service/AuthTokenProviderTest.java
  • src/test/java/com/example/solidconnection/auth/service/TokenBlackListServiceTest.java
  • src/main/java/com/example/solidconnection/auth/service/TokenProvider.java
  • src/main/java/com/example/solidconnection/auth/service/SignInService.java
  • src/main/java/com/example/solidconnection/auth/service/AuthTokenProvider.java
  • src/main/java/com/example/solidconnection/auth/token/JwtTokenProvider.java
  • src/main/java/com/example/solidconnection/auth/service/AccessToken.java
  • src/test/java/com/example/solidconnection/auth/service/JwtTokenProviderTest.java
  • src/main/java/com/example/solidconnection/auth/controller/AuthController.java
  • src/test/java/com/example/solidconnection/auth/service/AuthServiceTest.java
  • src/main/java/com/example/solidconnection/auth/service/AuthService.java
⏰ 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
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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 generate unit tests to generate unit tests for 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.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

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 UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 80985c0 and 1c861d0.

📒 Files selected for processing (11)
  • src/main/java/com/example/solidconnection/auth/controller/AuthController.java (1 hunks)
  • src/main/java/com/example/solidconnection/auth/service/AccessToken.java (1 hunks)
  • src/main/java/com/example/solidconnection/auth/service/AuthService.java (2 hunks)
  • src/main/java/com/example/solidconnection/auth/service/AuthTokenProvider.java (2 hunks)
  • src/main/java/com/example/solidconnection/auth/service/SignInService.java (1 hunks)
  • src/main/java/com/example/solidconnection/auth/service/TokenProvider.java (1 hunks)
  • src/main/java/com/example/solidconnection/auth/token/JwtTokenProvider.java (2 hunks)
  • src/test/java/com/example/solidconnection/auth/service/AuthServiceTest.java (5 hunks)
  • src/test/java/com/example/solidconnection/auth/service/AuthTokenProviderTest.java (5 hunks)
  • src/test/java/com/example/solidconnection/auth/service/JwtTokenProviderTest.java (1 hunks)
  • src/test/java/com/example/solidconnection/auth/service/TokenBlackListServiceTest.java (2 hunks)
🔇 Additional comments (27)
src/main/java/com/example/solidconnection/auth/service/TokenProvider.java (1)

11-11: 인터페이스 확장이 깔끔하게 구현되었습니다!

커스텀 클레임을 지원하는 오버로드 메서드 추가로 역할 정보를 토큰에 포함할 수 있게 되었네요. 기존 메서드와의 호환성을 유지하면서 기능을 확장한 좋은 설계입니다.

src/main/java/com/example/solidconnection/auth/service/SignInService.java (1)

19-19: 사용자 역할 정보가 액세스 토큰에 성공적으로 포함되었습니다!

siteUser.getRole()을 추가하여 토큰 생성 시 역할 정보를 전달하도록 수정된 부분이 PR 목표와 정확히 일치합니다. 프론트엔드에서 멘토/멘티 탭 구현이 훨씬 편리해질 것 같네요.

src/main/java/com/example/solidconnection/auth/service/AccessToken.java (1)

3-3: AccessToken 레코드 구조가 체계적으로 개선되었습니다!

다음과 같이 변경사항들이 잘 구성되어 있네요:

  1. Role 임포트 추가 - 필요한 의존성을 명확히 추가
  2. Role 필드 추가 - 레코드에 역할 정보를 포함하여 토큰 구조 확장
  3. 편의 생성자 제공 - String과 Role을 받아 Subject 객체를 자동 생성하는 깔끔한 구현

레코드의 불변성을 유지하면서 기능을 확장한 좋은 설계입니다.

Also applies to: 7-7, 11-12

src/main/java/com/example/solidconnection/auth/controller/AuthController.java (1)

116-116: 토큰 재발급에서 사용자 역할 정보 처리가 올바르게 구현되었습니다!

다음 변경사항들이 잘 연결되어 있네요:

  1. 사용자 ID 파라미터 추가 - @AuthorizedUser long siteUserId로 인증된 사용자 식별
  2. 서비스 호출 업데이트 - authService.reissue(siteUserId, reissueRequest)로 사용자 ID 전달

이를 통해 토큰 재발급 시에도 사용자의 역할 정보가 포함된 액세스 토큰을 생성할 수 있게 되었습니다.

Also applies to: 119-119

src/test/java/com/example/solidconnection/auth/service/AuthTokenProviderTest.java (5)

7-7: Role 임포트 추가가 적절합니다.

토큰에 역할 정보를 포함하는 새로운 기능을 위해 필요한 임포트입니다.


36-46: 역할 정보를 포함한 액세스 토큰 생성 테스트가 잘 구현되었습니다.

  1. 역할 매개변수 추가로 새로운 토큰 생성 방식을 정확히 테스트
  2. assertAll을 사용한 다중 검증으로 테스트 가독성 향상
  3. 토큰의 주체, 역할, 유효성을 모두 검증하여 완전한 테스트 커버리지 제공

70-70: 일관된 Role 매개변수 추가가 적절합니다.

모든 테스트 메서드에서 Role.MENTEE를 일관되게 사용하여 새로운 메서드 시그니처와 호환성을 확보했습니다.


83-83: 테스트 시나리오에 맞는 Role 매개변수 추가입니다.

리프레시 토큰 삭제 테스트에서도 일관되게 역할 정보를 포함하여 실제 사용 패턴을 반영합니다.


97-97: Subject 추출 테스트의 Role 매개변수 추가가 적절합니다.

토큰에서 Subject를 추출하는 테스트에서도 새로운 메서드 시그니처를 정확히 반영했습니다.

src/test/java/com/example/solidconnection/auth/service/JwtTokenProviderTest.java (1)

38-78: 토큰 생성 테스트의 구조화가 우수합니다.

  1. 중첩 클래스로 관련 테스트들을 논리적으로 그룹화
  2. Subject만 있는 토큰과 커스텀 클레임이 있는 토큰을 각각 테스트
  3. JWT 클레임 파싱과 만료 시간 검증을 통한 완전한 토큰 유효성 확인
  4. 새로운 역할 기반 토큰 기능을 지원하는 테스트 커버리지 제공
src/main/java/com/example/solidconnection/auth/service/AuthTokenProvider.java (4)

4-4: Role 임포트 추가가 적절합니다.

역할 기반 토큰 생성을 위한 필수 의존성입니다.


6-6: Map 임포트로 클레임 처리를 지원합니다.

커스텀 클레임 맵 처리를 위해 필요한 임포트입니다.


16-16: ROLE_CLAIM_KEY 상수 정의가 우수한 설계입니다.

역할 클레임 키를 상수로 정의하여 유지보수성과 일관성을 확보했습니다.


21-26: 역할 정보를 포함한 액세스 토큰 생성이 완벽하게 구현되었습니다.

  1. 메서드 시그니처에 Role 매개변수 추가로 역할 기반 토큰 생성 지원
  2. 상수를 사용한 역할 클레임 키로 일관성 확보
  3. 커스텀 클레임 맵을 통해 역할 정보를 토큰에 포함
  4. AccessToken 레코드에 주체, 역할, 토큰 문자열을 모두 포함하여 완전한 토큰 정보 제공
src/test/java/com/example/solidconnection/auth/service/AuthServiceTest.java (5)

47-56: @beforeeach 설정으로 테스트 구조가 크게 개선되었습니다.

  1. 공통 테스트 픽스처를 한 곳에서 초기화하여 중복 코드 제거
  2. siteUser, subject, accessToken을 재사용 가능한 필드로 정의
  3. 역할 정보를 포함한 AccessToken 생성으로 새로운 토큰 구조 반영
  4. 테스트 유지보수성과 가독성 향상

74-74: 탈퇴 메서드 호출에 사용자 ID 매개변수 추가가 적절합니다.

새로운 AuthService.quit 메서드 시그니처에 맞춰 정확히 업데이트되었습니다.


97-97: 토큰 재발급 메서드 호출에 사용자 ID 매개변수 추가가 정확합니다.

AuthService.reissue 메서드의 새로운 시그니처를 올바르게 반영했습니다.


112-112: 예외 시나리오 테스트에서도 일관된 매개변수 사용입니다.

잘못된 리프레시 토큰 테스트에서도 새로운 메서드 시그니처를 정확히 적용했습니다.


108-108: 공유 accessToken 사용으로 테스트 일관성이 향상되었습니다.

잘못된 리프레시 토큰 테스트에서 공유 픽스처를 사용하여 테스트 구조의 일관성을 유지했습니다.

src/main/java/com/example/solidconnection/auth/token/JwtTokenProvider.java (4)

13-13: Map 임포트로 커스텀 클레임 지원을 추가했습니다.

커스텀 클레임 맵 처리를 위한 필수 의존성입니다.


27-29: 기존 generateToken 메서드의 위임 패턴이 우수합니다.

빈 클레임 맵으로 헬퍼 메서드에 위임하여 기존 API 호환성을 유지하면서 새로운 기능을 지원합니다.


31-34: 커스텀 클레임을 지원하는 오버로드 메서드가 완벽합니다.

  1. Map<String, String> customClaims 매개변수로 역할 정보 등 커스텀 클레임 지원
  2. 동일한 헬퍼 메서드에 위임하여 코드 중복 방지
  3. TokenProvider 인터페이스 구현으로 계약 준수

36-47: JWT 토큰 생성 헬퍼 메서드가 훌륭하게 설계되었습니다.

  1. subject, claims, expireTime을 매개변수로 받아 유연한 토큰 생성 지원
  2. JWT Claims 객체에 커스텀 클레임을 추가하여 역할 정보 포함
  3. 현재 시간과 만료 시간을 정확히 설정
  4. HS512 알고리즘으로 안전한 토큰 서명
  5. 코드 중복을 제거하고 재사용성을 높인 우수한 리팩토링
src/main/java/com/example/solidconnection/auth/service/AuthService.java (1)

61-61: reissue 호출부 일관성 검증 완료

변경된 reissue 메서드 호출부의 일관성을 모두 검증했습니다. AuthController와 테스트 코드에서 siteUserId가 올바르게 전달되고 있습니다. 다음과 같이 호출부를 확인했습니다:

  1. AuthController.reissueToken
    • siteUserId와 ReissueRequest 파라미터가 모두 전달됨
  2. AuthServiceTest.reissue
    • siteUser.getId()를 활용해 재발급 로직 테스트 통과

위 검증 결과, 모든 호출부가 새로운 시그니처와 일치합니다. 변경 사항을 승인합니다.

src/test/java/com/example/solidconnection/auth/service/TokenBlackListServiceTest.java (3)

7-7: 테스트 가독성과 새로운 역할 기반 토큰 지원이 잘 구현되었습니다.

다음과 같은 개선사항들이 적절히 적용되었습니다:

1. Role 임포트 추가로 새로운 AccessToken 구조 지원
2. @DisplayName 어노테이션으로 테스트 클래스 설명 개선  
3. @BeforeEach 임포트로 테스트 설정 메서드 지원

Also applies to: 9-10, 16-16


26-26: 테스트 객체 생성을 중앙화한 리팩토링이 훌륭합니다.

다음과 같은 개선사항들이 잘 적용되었습니다:

1. 공통 AccessToken 필드 선언으로 테스트 간 일관성 확보
2. @BeforeEach를 활용한 테스트 설정 메서드로 중복 제거
3. Role.MENTEE를 포함한 새로운 AccessToken 생성자 사용

이러한 변경으로 테스트 유지보수성이 크게 향상되었고, 각 테스트마다 새로운 토큰 인스턴스를 보장합니다.

Also applies to: 28-31


37-37: 기존 테스트 로직과의 매끄러운 통합이 완료되었습니다.

중앙화된 accessToken 필드 사용으로 다음과 같은 이점들을 얻었습니다:

1. 모든 테스트 메서드에서 일관된 토큰 인스턴스 사용
2. 기존 테스트 로직의 변경 없이 리팩토링 완료
3. 테스트의 가독성과 유지보수성 향상

테스트 기능은 그대로 유지하면서 코드 구조만 개선된 훌륭한 리팩토링입니다.

Also applies to: 51-51, 54-54, 60-60

@nayonsoso nayonsoso self-assigned this Jul 26, 2025
Copy link
Contributor

@Gyuhyeok99 Gyuhyeok99 left a comment

Choose a reason for hiding this comment

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

고생하셨습니다!
그런데 문제가 될 거 같진 않지만 혹시 권한 변경 시 기존 토큰들 무효화를 시켜야할까요? 아니면 이거에 대해선 권한 변경이 딱히 저희 서비스에서 없으니 무시해도 괜찮을까요?

Copy link
Member

@whqtker whqtker left a comment

Choose a reason for hiding this comment

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

고생하셨습니다 ~ 토큰 생성 로직을 하나로 합쳐는 것도 좋은 변경이라고 생각합니다 !

@nayonsoso nayonsoso force-pushed the feat/406-accesstoken-include-role-claim branch from 1c861d0 to e48e8e7 Compare July 28, 2025 17:38
@nayonsoso nayonsoso merged commit 66aa670 into solid-connection:develop Jul 28, 2025
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat: access token이 role을 claim으로 갖도록

3 participants