Skip to content

[refactor] jwt 검증 로직 적용#80

Merged
jeongmallro merged 1 commit intodevfrom
refactor/jwt-#79
Jan 17, 2025
Merged

[refactor] jwt 검증 로직 적용#80
jeongmallro merged 1 commit intodevfrom
refactor/jwt-#79

Conversation

@lsh2613
Copy link
Contributor

@lsh2613 lsh2613 commented Jan 17, 2025

⭐ Summary

#79


📌 Tasks

  1. jwt 발급 api 구현
  2. jwt 검증 로직 적용
  3. swagger jwt 적용 코드 추가

- jwt 발급 api 구현
- jwt 검증 로직 적용
- swagger jwt 적용 코드 추가
@coderabbitai
Copy link

coderabbitai bot commented Jan 17, 2025

📝 Walkthrough

워크스루

이 풀 리퀘스트는 Docker 컴포즈 파일 추가, Swagger 보안 구성 업데이트, 새로운 토큰 컨트롤러 생성, JWT 인증 필터 개선 등의 변경 사항을 포함합니다. Docker 컴포즈 파일은 데이터베이스, Redis, 애플리케이션 서비스를 정의하고, Swagger 구성은 JWT 보안 스키마를 활성화했으며, 토큰 컨트롤러는 개발 목적의 토큰 발급 엔드포인트를 제공합니다.

변경 사항

파일 변경 요약
docker-compose.yml MySQL, Redis, 애플리케이션 서비스 추가, pitchain-network 네트워크 생성
src/main/java/com/pitchain/common/config/SwaggerConfig.java JWT 보안 스키마 구성 활성화, 보안 요구사항 추가
src/main/java/com/pitchain/controller/TokenController.java 새로운 토큰 발급 컨트롤러 생성, /token 엔드포인트 추가
src/main/java/com/pitchain/jwt/JwtAuthenticationFilter.java 토큰 검증 로직 개선, 화이트리스트에 /token 엔드포인트 추가

시퀀스 다이어그램

sequenceDiagram
    participant Client
    participant TokenController
    participant TokenUtil
    participant JwtAuthenticationFilter

    Client->>TokenController: GET /token?id=123
    TokenController->>TokenUtil: 토큰 발급
    TokenUtil-->>TokenController: 토큰 반환
    TokenController-->>Client: 토큰 응답
    
    Client->>JwtAuthenticationFilter: 요청 with 토큰
    JwtAuthenticationFilter->>JwtAuthenticationFilter: 토큰 검증
    JwtAuthenticationFilter-->>Client: 인증 처리
Loading

관련 가능한 풀 리퀘스트

제안된 리뷰어

  • jeongmallro

Finishing Touches

  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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. (Beta)
  • @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: 4

🧹 Nitpick comments (4)
src/main/java/com/pitchain/common/config/SwaggerConfig.java (1)

31-31: API 문서에 인증 관련 설명 추가 필요

보안 요구사항이 기술적으로는 잘 구성되어 있으나, API 사용자를 위한 인증 프로세스에 대한 설명이 부족합니다.

다음과 같은 내용을 추가하는 것을 고려해보세요:

                 .addSecurityItem(new SecurityRequirement().addList(AUTHORIZATION))
+                .info(new Info()
+                        .description("JWT 인증 가이드:\n" +
+                                   "1. /token 엔드포인트에서 액세스 토큰을 발급받습니다.\n" +
+                                   "2. 발급받은 토큰을 Authorization 헤더에 'Bearer {token}' 형식으로 포함시켜 요청합니다."))
                 .externalDocs(new ExternalDocumentation()
src/main/java/com/pitchain/jwt/JwtAuthenticationFilter.java (1)

28-32: 화이트리스트 구성 개선 제안

현재 화이트리스트가 단순 배열로 관리되고 있습니다. 더 체계적인 관리를 위한 개선이 필요합니다.

다음과 같은 상수 그룹화를 고려해보세요:

-    public static final String[] whitelist = {
-            "/oauth**",
-            "/resources/**", "/favicon.ico", // resource
-            "/swagger-ui/**", "/api-docs/**", "/v3/api-docs**", "/v3/api-docs/**", // swagger
-            "/token" // todo 배포 시 삭제
-    };
+    public static final String[] SWAGGER_PATHS = {
+            "/swagger-ui/**",
+            "/api-docs/**",
+            "/v3/api-docs**",
+            "/v3/api-docs/**"
+    };
+    
+    public static final String[] RESOURCE_PATHS = {
+            "/resources/**",
+            "/favicon.ico"
+    };
+    
+    public static final String[] AUTH_PATHS = {
+            "/oauth**"
+    };
+    
+    public static final String[] whitelist = Stream.of(
+            SWAGGER_PATHS,
+            RESOURCE_PATHS,
+            AUTH_PATHS,
+            new String[]{"/token"} // todo 배포 시 삭제
+    ).flatMap(Arrays::stream).toArray(String[]::new);
src/main/java/com/pitchain/controller/TokenController.java (1)

16-16: API 문서 개선 필요

현재 API 문서에는 중요한 사용 정보가 누락되어 있습니다.

다음과 같이 자세한 API 문서를 추가하세요:

-    @Operation(summary = "토큰 발급 / 개발용")
+    @Operation(
+        summary = "토큰 발급 / 개발용",
+        description = "개발 환경에서만 사용 가능한 토큰 발급 API입니다.\n" +
+                     "- 유효한 사용자 ID만 사용 가능\n" +
+                     "- 발급된 토큰은 Authorization 헤더에 Bearer 형식으로 포함\n" +
+                     "- 프로덕션 환경에서는 사용 불가",
+        parameters = {
+            @Parameter(name = "id", description = "사용자 ID (1 이상의 양수)", required = true)
+        }
+    )
docker-compose.yml (1)

35-36: 네트워크 보안 구성 개선 필요

네트워크 구성이 기본적인 수준입니다. 보안을 강화하기 위한 추가 설정이 필요합니다.

다음과 같은 네트워크 구성을 고려하세요:

 networks:
   pitchain-network:
+    driver: bridge
+    internal: true  # 외부 네트워크와 격리
+    ipam:
+      driver: default
+      config:
+        - subnet: 172.20.0.0/16
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7f95339 and 4a00dd6.

⛔ Files ignored due to path filters (1)
  • koreaexim.pem is excluded by !**/*.pem
📒 Files selected for processing (4)
  • docker-compose.yml (1 hunks)
  • src/main/java/com/pitchain/common/config/SwaggerConfig.java (1 hunks)
  • src/main/java/com/pitchain/controller/TokenController.java (1 hunks)
  • src/main/java/com/pitchain/jwt/JwtAuthenticationFilter.java (3 hunks)
🔇 Additional comments (2)
src/main/java/com/pitchain/common/config/SwaggerConfig.java (1)

22-31: JWT 보안 구성이 올바르게 설정되었습니다.

Swagger에 JWT 인증이 적절하게 구성되어 있습니다. Bearer 토큰 형식과 보안 요구사항이 정확하게 설정되었습니다.

src/main/java/com/pitchain/jwt/JwtAuthenticationFilter.java (1)

44-49: 토큰 검증 로직이 적절하게 구현되었습니다.

토큰 누락 체크와 JWT 디코딩, 사용자 ID 추출 과정이 안전하게 구현되어 있습니다.

Comment on lines +31 to +32
"/swagger-ui/**", "/api-docs/**", "/v3/api-docs**", "/v3/api-docs/**", // swagger
"/token" // todo 배포 시 삭제
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

개발용 엔드포인트에 대한 보안 우려

/token 엔드포인트가 화이트리스트에 포함되어 있고 TODO 주석에 배포 시 삭제한다고 명시되어 있습니다. 이는 보안상 중요한 사항입니다.

배포 환경별로 화이트리스트를 분리하는 것을 권장합니다:

-            "/token" // todo 배포 시 삭제
+            #if DEV_PROFILE
+            "/token"
+            #endif

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +16 to +20
@Operation(summary = "토큰 발급 / 개발용")
@GetMapping("/token")
public CustomApiResponse<String> token(@RequestParam Long id) {
return CustomApiResponse.onSuccess(tokenUtil.issueAccessToken(id));
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

토큰 발급 엔드포인트의 보안 강화 필요

현재 구현은 다음과 같은 보안 문제가 있습니다:

  1. ID 파라미터에 대한 유효성 검증이 없습니다
  2. 토큰 발급 요청에 대한 접근 제어가 없습니다
  3. 개발용임에도 프로덕션 환경에서 실행될 수 있습니다

다음과 같은 보안 강화를 권장합니다:

+    @Profile("dev")
     @Operation(summary = "토큰 발급 / 개발용")
     @GetMapping("/token")
     public CustomApiResponse<String> token(@RequestParam Long id) {
+        if (id == null || id <= 0) {
+            throw new GeneralHandler(ErrorStatus.INVALID_USER_ID);
+        }
+        // 개발 환경의 허용된 테스트 ID 목록과 대조
+        if (!DEV_TEST_IDS.contains(id)) {
+            throw new GeneralHandler(ErrorStatus.UNAUTHORIZED_ACCESS);
+        }
         return CustomApiResponse.onSuccess(tokenUtil.issueAccessToken(id));
     }

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +4 to +15
database:
container_name: pitchain_db
image: mysql
environment:
MYSQL_DATABASE: pitchain_db
MYSQL_ROOT_HOST: '%'
MYSQL_ROOT_PASSWORD: 1234
ports:
- "3306:3306"
command: ["--character-set-server=utf8mb4","--collation-server=utf8mb4_unicode_ci"]
networks:
- pitchain-network
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

데이터베이스 컨테이너 구성 개선 필요

데이터 지속성과 건강 검사가 구성되어 있지 않습니다.

다음과 같은 구성을 추가하세요:

   database:
     container_name: pitchain_db
     image: mysql
+    volumes:
+      - db_data:/var/lib/mysql
+    healthcheck:
+      test: ["CMD", "mysqladmin", "ping", "-h", "localhost"]
+      interval: 10s
+      timeout: 5s
+      retries: 5
     environment:
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
database:
container_name: pitchain_db
image: mysql
environment:
MYSQL_DATABASE: pitchain_db
MYSQL_ROOT_HOST: '%'
MYSQL_ROOT_PASSWORD: 1234
ports:
- "3306:3306"
command: ["--character-set-server=utf8mb4","--collation-server=utf8mb4_unicode_ci"]
networks:
- pitchain-network
database:
container_name: pitchain_db
image: mysql
volumes:
- db_data:/var/lib/mysql
healthcheck:
test: ["CMD", "mysqladmin", "ping", "-h", "localhost"]
interval: 10s
timeout: 5s
retries: 5
environment:
MYSQL_DATABASE: pitchain_db
MYSQL_ROOT_HOST: '%'
MYSQL_ROOT_PASSWORD: 1234
ports:
- "3306:3306"
command: ["--character-set-server=utf8mb4","--collation-server=utf8mb4_unicode_ci"]
networks:
- pitchain-network

Comment on lines +8 to +10
MYSQL_DATABASE: pitchain_db
MYSQL_ROOT_HOST: '%'
MYSQL_ROOT_PASSWORD: 1234
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

데이터베이스 보안 구성 개선 필요

환경 변수에 하드코딩된 데이터베이스 자격 증명이 있습니다.

다음과 같은 보안 개선을 권장합니다:

     environment:
       MYSQL_DATABASE: pitchain_db
       MYSQL_ROOT_HOST: '%'
-      MYSQL_ROOT_PASSWORD: 1234
+      MYSQL_ROOT_PASSWORD: ${DB_ROOT_PASSWORD}
+      MYSQL_USER: ${DB_USER}
+      MYSQL_PASSWORD: ${DB_PASSWORD}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
MYSQL_DATABASE: pitchain_db
MYSQL_ROOT_HOST: '%'
MYSQL_ROOT_PASSWORD: 1234
MYSQL_DATABASE: pitchain_db
MYSQL_ROOT_HOST: '%'
MYSQL_ROOT_PASSWORD: ${DB_ROOT_PASSWORD}
MYSQL_USER: ${DB_USER}
MYSQL_PASSWORD: ${DB_PASSWORD}

@jeongmallro jeongmallro merged commit d1946af into dev Jan 17, 2025
2 checks passed
@coderabbitai coderabbitai bot mentioned this pull request Jul 14, 2025
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