Skip to content

Conversation

@fivedragon5
Copy link
Member

@fivedragon5 fivedragon5 commented Jan 4, 2026

#️⃣연관된 이슈

close #343

📝 작업 내용

임시 AccessToken 발급 작업의 연장선으로 Token 처리 방식을 개선했습니다.

1. accessToken 처리 방식 개선

  • accessToken은 선택 인증 토큰으로 처리
  • 유효한 경우에만 Authentication을 설정
  • 유효하지 않은 경우:
  • accessToken 쿠키 삭제
  • SecurityContext 정리
  • 요청은 계속 진행 (permitAll API 정상 동작)

2. verificationToken 처리 명확화 (의도적 인증)

  • verificationToken은 반드시 유효해야 하는 토큰으로 유지
  • 유효하지 않은 경우 AuthException 발생
  • 이메일 인증 등 의도적인 인증 플로우에만 사용

3. 쿠키 삭제 로직 공통화

  • accessToken / verificationToken 삭제 로직의 중복을 제거
  • 쿠키 이름만 전달받는 공통 메서드로 분리

Summary by CodeRabbit

릴리스 노트

  • 버그 수정

    • 인증 토큰 검증 실패 시 불필요한 토큰을 자동으로 제거하여 로그인 상태 관리 개선
    • 잘못된 인증 토큰에 대한 명확한 오류 처리 추가
  • 개선 사항

    • 접근 토큰과 인증 토큰 처리 흐름을 분리하여 보안 강화
    • 세션 정보 관리의 안정성 향상

✏️ Tip: You can customize this high-level summary in your review settings.

@fivedragon5 fivedragon5 requested a review from 023-dev January 4, 2026 06:09
@fivedragon5 fivedragon5 self-assigned this Jan 4, 2026
@fivedragon5 fivedragon5 linked an issue Jan 4, 2026 that may be closed by this pull request
@coderabbitai
Copy link

coderabbitai bot commented Jan 4, 2026

개요

JWT 인증 필터가 액세스 토큰과 검증 토큰을 처리하기 위해 별도의 제어 경로를 포함하도록 재구성되었습니다. 토큰 검증 실패 시 쿠키가 명확하게 삭제되고, 검증 토큰용 전문화된 인증 경로가 추가되었으며, 구조화된 오류 처리가 도입되었습니다.

변경 사항

내용 / 파일(들) 변경 요약
JWT 인증 필터 개선
src/main/java/org/ject/support/common/security/jwt/JwtAuthenticationFilter.java
액세스 토큰 검증 실패 시 쿠키 및 SecurityContext 정리; 검증 토큰용 별도 처리 경로 추가; 전용 쿠키 삭제 헬퍼(clearAuthCookie) 도입; 명시적 INVALID_TOKEN 예외 처리; 모든 경우에 다음 필터로 진행

시퀀스 다이어그램

sequenceDiagram
    participant Client
    participant Filter as JwtAuthenticationFilter
    participant TokenValidator as Token Validator
    participant SecurityMgr as SecurityContext Manager
    participant CookieMgr as Cookie Manager

    Client->>Filter: HTTP 요청 (Access/Verification Token)
    
    rect rgb(230, 245, 250)
        Note over Filter,CookieMgr: 액세스 토큰 처리
        Filter->>TokenValidator: 액세스 토큰 검증
        alt 검증 성공
            TokenValidator-->>Filter: 유효한 토큰
            Filter->>SecurityMgr: SecurityContext에 인증 설정
        else 검증 실패
            TokenValidator-->>Filter: 검증 오류
            Filter->>CookieMgr: 액세스 토큰 쿠키 삭제
            Filter->>SecurityMgr: SecurityContext 초기화
        end
    end
    
    rect rgb(245, 240, 245)
        Note over Filter,SecurityMgr: 검증 토큰 처리
        Filter->>Filter: 검증 토큰 존재 확인
        alt 검증 토큰 있음
            Filter->>TokenValidator: 검증 토큰 검증
            alt 검증 성공
                TokenValidator-->>Filter: 이메일 추출
                Filter->>SecurityMgr: 검증용 전문화된 인증 설정
            else 검증 실패
                TokenValidator-->>Filter: INVALID_TOKEN 예외
                Filter->>CookieMgr: 검증 토큰 쿠키 삭제
            end
        end
    end
    
    Filter->>Filter: 다음 필터로 진행 (chain.doFilter)
    Filter-->>Client: HTTP 응답
Loading

코드 리뷰 소요 시간

🎯 4 (복잡함) | ⏱️ ~45분

🐰 JWT의 길을 정리했네요,
토큰 둘이 각각의 길을 가고,
실패할 땐 쿠키를 정중히 비우고,
보안 문맥은 깨끗이 초기화하니,
인증 흐름이 명확하게 춤을 춘답니다! ✨🔐

Pre-merge checks and finishing touches

❌ Failed checks (2 warnings)
Check name Status Explanation Resolution
Linked Issues check ⚠️ Warning 풀 리퀘스트는 Issue #343의 주요 요구사항(액세스 토큰 선택적 처리, 검증 토큰 필수 처리, 일관된 오류 처리)을 구현했으나, URL 권한별 정리 및 prefix 설정 요구사항은 미구현 상태입니다. Issue #343에서 명시된 권한별 URL 정리(ADMIN, SEMESTER, APPLY, VERIFICATION) 및 prefix 설정을 통한 필터 권한 처리 로직을 추가로 구현 필요합니다.
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed 제목이 JWT 인증 필터의 액세스 토큰 및 검증 토큰 처리 로직 개선을 명확하게 설명하며, 변경 사항의 핵심을 적절히 요약하고 있습니다.
Out of Scope Changes check ✅ Passed 모든 코드 변경사항이 JWT 인증 필터 개선과 관련하여 범위 내에 있으며, 연관되지 않은 외부 변경사항이 없습니다.
✨ 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

Comment @coderabbitai help to get the list of available commands and usage tips.

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/main/java/org/ject/support/common/security/jwt/JwtAuthenticationFilter.java (1)

69-84: 예외 처리 로직에서 AuthException이 손실됩니다.

Line 69에서 던진 AuthException(AuthErrorCode.INVALID_TOKEN)이 Line 80의 catch 블록에서 잡혀 GlobalException(GlobalErrorCode.INVALID_ACCESS_TOKEN)으로 변환됩니다. 이로 인해 verification token 관련 에러가 access token 에러로 잘못 표시됩니다.

또한, chain.doFilter()에서 발생하는 IOException/ServletExceptionINVALID_ACCESS_TOKEN으로 변환되어 실제 오류 원인을 파악하기 어렵습니다.

🔎 AuthException을 별도로 처리하는 수정 제안
         chain.doFilter(request, response);

+    } catch (AuthException e) {
+        log.error("JWT 인증 처리 중 에러 발생", e);
+        SecurityContextHolder.clearContext();
+        throw e;
     } catch (Exception e) {
         log.error("JWT 인증 처리 중 에러 발생", e);
         SecurityContextHolder.clearContext();
         throw new GlobalException(GlobalErrorCode.INVALID_ACCESS_TOKEN);
     }
🧹 Nitpick comments (1)
src/main/java/org/ject/support/common/security/jwt/JwtAuthenticationFilter.java (1)

99-106: 쿠키에 SameSite 속성이 누락되었습니다.

CSRF 공격 방지를 위해 SameSite 속성을 설정하는 것이 권장됩니다. Java의 Cookie 클래스는 SameSite를 직접 지원하지 않으므로, Set-Cookie 헤더를 직접 구성하거나 Spring의 ResponseCookie를 사용해야 합니다.

🔎 ResponseCookie를 사용한 수정 제안
+import org.springframework.http.ResponseCookie;
 private void clearAuthCookie(HttpServletResponse response, String cookieName) {
-    Cookie cookie = new Cookie(cookieName, null);
-    cookie.setMaxAge(0);
-    cookie.setPath("/");
-    cookie.setHttpOnly(true);
-    cookie.setSecure(true);
-    response.addCookie(cookie);
+    ResponseCookie cookie = ResponseCookie.from(cookieName, "")
+            .maxAge(0)
+            .path("/")
+            .httpOnly(true)
+            .secure(true)
+            .sameSite("Strict")
+            .build();
+    response.addHeader("Set-Cookie", cookie.toString());
 }
📜 Review details

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9516df2 and 25e3d2d.

📒 Files selected for processing (1)
  • src/main/java/org/ject/support/common/security/jwt/JwtAuthenticationFilter.java
🧰 Additional context used
🪛 ast-grep (0.40.3)
src/main/java/org/ject/support/common/security/jwt/JwtAuthenticationFilter.java

[warning] 104-104: The application does not appear to verify inbound requests which can lead to a Cross-site request forgery (CSRF) vulnerability. If the application uses cookie-based authentication, an attacker can trick users into sending authenticated HTTP requests without their knowledge from any arbitrary domain they visit. To prevent this vulnerability start by identifying if the framework or library leveraged has built-in features or offers plugins for CSRF protection. CSRF tokens should be unique and securely random. The Synchronizer Token or Double Submit Cookie patterns with defense-in-depth mechanisms such as the sameSite cookie flag can help prevent CSRF. For more information, see: [Cross-site request forgery prevention](https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Req\ uest_Forgery_Prevention_Cheat_Sheet.html).
Context: response.addCookie(cookie);
Note: [CWE-352] Cross-Site Request Forgery (CSRF). [REFERENCES]
- https://stackoverflow.com/questions/42717210/samesite-cookie-in-java-application

(cookie-missing-samesite-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: check-application
🔇 Additional comments (1)
src/main/java/org/ject/support/common/security/jwt/JwtAuthenticationFilter.java (1)

50-76: 두 토큰이 동시에 존재할 경우의 동작 확인 필요.

accessTokenverificationToken이 모두 유효한 경우, verification 인증이 access token 인증을 덮어씁니다. 이것이 의도된 동작인지 확인해 주세요.

만약 두 토큰이 동시에 존재하면 안 되는 경우라면, 명시적인 검증 로직을 추가하는 것이 좋습니다.

@github-actions
Copy link

github-actions bot commented Jan 4, 2026

Test Results

250 tests  ±0   250 ✅ ±0   9s ⏱️ ±0s
 55 suites ±0     0 💤 ±0 
 55 files   ±0     0 ❌ ±0 

Results for commit 25e3d2d. ± Comparison against base commit 9516df2.

@github-actions
Copy link

github-actions bot commented Jan 4, 2026

📊테스트 커버리지

Overall Project 79.92% -0.57% 🍏
Files changed 19.61%

File Coverage
JwtAuthenticationFilter.java 20.34% -34.75%

Copy link
Member

@023-dev 023-dev left a comment

Choose a reason for hiding this comment

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

고생하셨습니다.

@fivedragon5 fivedragon5 merged commit dcba09e into dev Jan 4, 2026
3 checks passed
@fivedragon5 fivedragon5 deleted the feat/343-feat-jwtexceptionhandlerfilter branch January 4, 2026 09:23
@fivedragon5 fivedragon5 restored the feat/343-feat-jwtexceptionhandlerfilter branch January 4, 2026 11:35
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] JwtExceptionHandlerFilter 개선

3 participants