Skip to content

Refactor/#199#200

Merged
jeongmallro merged 7 commits intodevfrom
refactor/#199
Jul 15, 2025
Merged

Refactor/#199#200
jeongmallro merged 7 commits intodevfrom
refactor/#199

Conversation

@lsh2613
Copy link
Contributor

@lsh2613 lsh2613 commented Jul 14, 2025

⭐ Summary

#199


📌 Tasks

  1. JwtAuthenticationFilter에 재발급 로직 추가
  2. JwtAuthenticationFilter는 인증, Security는 인가에 대한 책임만 수행하도록 분할
    • JwtAuthenticationFilter는 jwt가 존재하면 검증 후 securityContext에 권한 부여만 해줌 (에러 반환 X, 권한 체크X)
    • 이제 권한이 필요 없는 API에 대한 정보는 security에만 존재
  3. 인가 실패에 대한 에러 응답 메시지 추가
  4. MemberRole의 내부 roles를 enum으로 관리

@lsh2613 lsh2613 requested a review from jeongmallro July 14, 2025 13:38
@lsh2613 lsh2613 self-assigned this Jul 14, 2025
@coderabbitai
Copy link

coderabbitai bot commented Jul 14, 2025

📝 Walkthrough

Walkthrough

이 변경사항은 인증 및 권한 부여, JWT 토큰 검증, 역할 관리, 그리고 일부 API 엔드포인트 경로에 대한 리팩토링을 포함합니다. 보안 설정이 세분화되고, JWT 필터와 Redis 유틸리티가 토큰 재발급 및 검증 로직을 개선하며, 역할 Enum 구조가 변경되었습니다.

Changes

파일/그룹 변경 요약
.../collector/RoleRequestCollector.java AnnotatedElementUtils 대신 직접 getAnnotation 사용하여 RequiredRole 어노테이션 조회 방식 단순화.
.../config/SecurityConfig.java 화이트리스트를 Swagger, 정적 리소스, 공개 API로 분리. 인증 실패/권한 거부시 JSON 에러 응답 핸들러 추가.
.../constant/MemberRole.java 역할 문자열 배열을 EnumSet<RoleType>으로 변경, RoleType enum 추가, 역할 조회 메서드 추가.
.../filter/JwtAuthenticationFilter.java 화이트리스트 기반 필터링 제거, access/refresh 토큰 검증 및 재발급 로직으로 변경, MemberClaims 사용.
.../redis/RedisTokenUtil.java 토큰 클레임 파싱 메서드 일반화, 역할 변환 로직 개선, 토큰 재발급 및 응답 헤더 설정 메서드 추가.
.../investment/presentation/InvestmentController.java 투자 상태 조회 API 경로를 /investment에서 /investments로 변경.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant JwtFilter as JwtAuthenticationFilter
    participant RedisUtil as RedisTokenUtil
    participant SecurityContext

    Client->>JwtFilter: 요청 전송 (Access/Refresh 토큰 포함)
    JwtFilter->>JwtFilter: Access 토큰 검증 시도
    alt Access 토큰 유효
        JwtFilter->>SecurityContext: 인증 정보 설정
        JwtFilter->>Client: 요청 처리 계속
    else Access 토큰 만료/실패
        JwtFilter->>JwtFilter: Refresh 토큰 검증 시도
        alt Refresh 토큰 유효
            JwtFilter->>RedisUtil: 토큰 재발급 및 응답 헤더 설정
            JwtFilter->>SecurityContext: 인증 정보 설정
            JwtFilter->>Client: 요청 처리 계속
        else Refresh 토큰도 실패
            JwtFilter->>Client: 인증 정보 없이 요청 처리
        end
    end
Loading

Possibly related PRs

  • [refactor] jwt 검증 로직 적용 #80: JWT 인증 필터 및 RedisTokenUtil의 JWT 검증·재발급 로직 리팩토링과 직접적으로 관련됨.
  • Refactor/176 #178: RoleRequestCollector에서 RequiredRole 어노테이션 단순 조회 및 역할 기반 인프라와 직접적으로 연관됨.
✨ 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: 6

🔭 Outside diff range comments (3)
src/main/java/com/pitchain/common/collector/RoleRequestCollector.java (1)

33-33: 프로덕션 코드에서 디버깅 출력문을 제거해주세요.

System.out.println() 문은 디버깅 목적으로 보이며, 프로덕션 코드에는 포함되어서는 안 됩니다.

-        System.out.println();
src/main/java/com/pitchain/common/redis/RedisTokenUtil.java (2)

67-67: Refresh 토큰 만료 시간 설정 오류

issueRefreshToken 메서드에서 accessTokenExpirationPeriod를 사용하고 있습니다. 이는 refreshTokenExpirationPeriod를 사용해야 합니다.

-                .withExpiresAt(new Date(System.currentTimeMillis() + accessTokenExpirationPeriod))
+                .withExpiresAt(new Date(System.currentTimeMillis() + refreshTokenExpirationPeriod))

77-77: Refresh 토큰 만료 시간 설정 오류 (테스트용 메서드)

issueRefreshTokenWithoutExpiration 메서드도 동일한 문제가 있습니다. 메서드명과 주석(3시간)이 일치하지 않으며, 하드코딩된 값을 사용하고 있습니다.

이 테스트용 메서드의 목적과 사용처를 재검토하고, 필요하다면 명확한 상수를 사용하거나 메서드명을 변경하는 것을 권장합니다.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c5085b3 and a3fb064.

📒 Files selected for processing (6)
  • src/main/java/com/pitchain/common/collector/RoleRequestCollector.java (1 hunks)
  • src/main/java/com/pitchain/common/config/SecurityConfig.java (4 hunks)
  • src/main/java/com/pitchain/common/constant/MemberRole.java (2 hunks)
  • src/main/java/com/pitchain/common/filter/JwtAuthenticationFilter.java (2 hunks)
  • src/main/java/com/pitchain/common/redis/RedisTokenUtil.java (2 hunks)
  • src/main/java/com/pitchain/investment/presentation/InvestmentController.java (1 hunks)
🔇 Additional comments (7)
src/main/java/com/pitchain/common/collector/RoleRequestCollector.java (1)

39-39: @RequiredRole 어노테이션 탐색 방식 변경 검토 결과
직접 @RequiredRole을 메타 어노테이션으로 사용한 정의가 없고, 상속(inherited)되어 사용되는 케이스도 확인되지 않았습니다. 따라서 AnnotatedElementUtils.findMergedAnnotation에서 getAnnotation으로 변경해도 문제 없습니다.

src/main/java/com/pitchain/investment/presentation/InvestmentController.java (1)

30-30: API 경로가 단수형에서 복수형으로 변경되었습니다.

RESTful 규칙에 따라 복수형을 사용하는 것이 좋은 변경사항입니다. 이제 POST와 GET 엔드포인트가 동일한 경로를 사용하여 일관성이 향상되었습니다.

다만, 이 변경사항이 기존 클라이언트에 영향을 줄 수 있으므로 클라이언트 업데이트가 필요한지 확인해주세요.

src/main/java/com/pitchain/common/redis/RedisTokenUtil.java (2)

129-138: 토큰 재발급 메서드 구현이 적절합니다.

새로운 access token과 refresh token을 발급하여 응답 헤더에 설정하는 로직이 명확하게 구현되었습니다.


122-127: 예외 처리 확인 완료
getClaim 메서드에서 던지는 JWTVerificationException은 다음과 같이 적절히 처리되고 있습니다:

  • JwtAuthenticationFilter#doFilterInternal:
    • Access 토큰 검증 실패 시 예외를 캐치하여 refresh 흐름 진입
    • Refresh 토큰 검증 실패 시 필터 체인으로 정상 요청 흐름 복귀
  • 컨트롤러 레이어:
    • GlobalExceptionHandler@ExceptionHandler(JWTVerificationException.class)에서 전역 처리

따라서 추가적인 try-catch 블록 삽입 없이도 예외가 안전하게 핸들링되므로 별도 조치는 필요하지 않습니다.

src/main/java/com/pitchain/common/constant/MemberRole.java (1)

15-50: 역할 관리 구조 개선

String[]에서 EnumSet<RoleType>으로의 리팩토링은 다음과 같은 장점이 있습니다:

  • 타입 안전성 향상
  • 컴파일 시점 오류 검출 가능
  • EnumSet의 효율적인 메모리 사용과 빠른 연산

구현이 깔끔하고 기존 API와의 호환성도 잘 유지되었습니다.

src/main/java/com/pitchain/common/config/SecurityConfig.java (2)

71-89: 보안 설정 화이트리스트 구조 개선

화이트리스트를 목적별로 분리한 것은 좋은 개선사항입니다:

  • Swagger UI 관련 경로
  • 정적 리소스 경로
  • 공개 API 엔드포인트

이렇게 분리하면 각 카테고리별로 권한을 다르게 설정하거나 관리하기 용이합니다.


105-119: 커스텀 예외 핸들러 구현

인증 실패와 권한 부족에 대한 커스텀 핸들러가 잘 구현되었습니다. 사용자 친화적인 한글 메시지를 제공하는 것도 좋습니다.

@jeongmallro jeongmallro merged commit fe4954e into dev Jul 15, 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.

2 participants