Skip to content

[hotfix] #170 - 크로스사이트 재발급 오류 수정 - #172

Merged
Jy000n merged 9 commits into
developfrom
hotfix/#170-reissue-error
Jul 15, 2026
Merged

Jy000n merged 9 commits into
developfrom
hotfix/#170-reissue-error

Conversation

@Jy000n

@Jy000n Jy000n commented Jul 15, 2026 •

Copy link
Copy Markdown
Member

관련 이슈 🛠

작업 내용 요약 ✏️

프로덕션 환경(프론트 timo-client.vercel.app ↔ 백엔드 api.timo.kr)에서 access token 재발급(/api/v1/auth/reissue)이 401로 실패하는 문제를 수정했습니다. 인증 쿠키의 SameSite 속성이 Strict로 설정되어 있어, 크로스사이트 XHR 요청 시 브라우저가 쿠키를 아예 전송하지 않아 발생한 문제였습니다.

주요 변경 사항 🛠️

  • [CookieUtil]: createCookie, expireCookie 두 메서드 모두 sameSite를 Strict에서 None으로 변경

트러블 슈팅 ⚽️

  • 프론트와 백엔드가 서로 다른 도메인(크로스사이트)으로 배포되어 있어, refreshToken 쿠키가 SameSite=Strict인 경우 axios를 통한 백그라운드 재발급 요청(XHR)에는 쿠키가 전송되지 않음을 확인함
  • 로그인 시에는 window.location.href를 통한 풀 페이지 리다이렉트(top-level navigation)라 Strict여도 우연히 통과되어, 재발급 단계에서만 문제가 드러났던 것으로 파악됨
  • SameSite=None은 Secure=true가 함께 있어야 브라우저가 쿠키를 인정하므로, 배포 환경의 cookie-secure 설정이 true인지, HTTPS로 서비스되고 있는지 별도 확인함
  • SameSite=None 전환에 따른 CSRF 노출 우려를 검토함. 현재 CORS 설정에서 allowedOrigins를 프론트 도메인으로 한정하고 allowCredentials(true)를 사용 중이며, 쿠키에는 이미 httpOnly(true)가 적용되어 있어 XSS를 통한 탈취 위험도 낮다고 함,,

  • Safari ITP로 인한 재발급 실패 문제를 완전히 해결하려면 프론트/백엔드 도메인 통일이 필요하다고 판단했으나, 즉시 적용 가능한 개선책으로 CHIPS(Partitioned Cookies) 속성을 우선 추가함
  • CHIPS는 Chrome 등 지원 브라우저에서는 크로스도메인 쿠키 문제를 완화하며, 다른 프론트 사이트와 refresh token을 공유할 계획이 없는 현재 구조에는 제약사항(멀티 사이트 공유 불가)이 문제되지 않음

테스트 결과 📄

스크린샷 📷

image

리뷰 요구사항 📢

📎 참고 자료 (선택)

Summary by CodeRabbit

요약(릴리스 노트)

  • 버그 수정

    • 인증 쿠키의 SameSite 정책을 secure 여부에 따라 동적으로 적용하도록 변경했습니다(쿠키 생성/만료 모두 동일 적용).
  • 보안 강화

    • 인증 관련 보호 경로 요청 시 Origin 헤더를 검증하고, 조건에 맞지 않으면 즉시 403으로 차단합니다.
    • Origin 검증이 기존 인증 처리보다 먼저 수행되도록 필터 실행 순서를 조정했습니다.

@coderabbitai

coderabbitai Bot commented Jul 15, 2026 •

Copy link
Copy Markdown

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Walkthrough

인증 쿠키의 SameSite와 partitioned 옵션을 secure 여부에 따라 설정하고, 보호된 인증 경로에 대한 Origin 검증 필터를 Spring Security 체인에 추가했습니다.

Changes

인증 보안 흐름

Layer / File(s) Summary
인증 쿠키 보안 옵션 변경
src/main/java/com/Timo/Timo/global/auth/utils/CookieUtil.java
createCookie와 expireCookie가 secure=true이면 SameSite=None과 partitioned=true를 사용하고, 그렇지 않으면 SameSite=Strict를 사용합니다.
보호 경로 Origin 검증 및 필터 등록
src/main/java/com/Timo/Timo/global/auth/filter/OriginValidationFilter.java, src/main/java/com/Timo/Timo/global/config/SecurityConfig.java
보호된 인증 경로의 Origin을 허용 URL 목록과 비교하고, 검증 필터를 JwtAuthenticationFilter 앞에 등록하며 자동 서블릿 필터 등록을 비활성화합니다.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant OriginValidationFilter
  participant JwtAuthenticationFilter
  Client->>OriginValidationFilter: 보호된 인증 경로 요청 및 Origin 전달
  OriginValidationFilter->>OriginValidationFilter: 허용 URL과 Origin 비교
  OriginValidationFilter->>JwtAuthenticationFilter: 검증 통과 요청 전달
  OriginValidationFilter-->>Client: 검증 실패 시 403 응답
Loading

Possibly related PRs

  • Team-Timo/Timo-Server#14: SecurityConfig의 JwtAuthenticationFilter 주변 필터 체인 변경과 관련됩니다.
  • Team-Timo/Timo-Server#18: 인증 기능 및 CookieUtil 옵션과 보호된 인증 경로 변경이 직접 연결됩니다.

Suggested reviewers: aneykrap, laura-jung

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed 제목이 크로스사이트 재발급 오류 수정이라는 핵심 변경을 간결하게 잘 요약합니다.
Linked Issues check ✅ Passed SameSite 수정과 SecurityConfig 연동이 재발급 오류 해결 및 보안 설정 요구사항과 일치합니다.
Out of Scope Changes check ✅ Passed 변경은 쿠키 SameSite/Partitioned와 인증 필터·보안 설정에 한정되어 요구 범위를 벗어난 내용이 보이지 않습니다.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch hotfix/#170-reissue-error

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.

@aneykrap aneykrap left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

어푸푸 입니둥

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/main/java/com/Timo/Timo/global/auth/utils/CookieUtil.java`:
- Line 14: CookieUtil의 SameSite("None") 설정으로 크로스사이트 쿠키 요청이 허용되므로, CSRF가 비활성화된
SecurityConfig에 방어 검증을 추가하세요. logout, withdraw, reissue 상태 변경 엔드포인트에서 CSRF 토큰 검증
또는 신뢰할 수 있는 Origin/Referer 검증을 적용하고, 정상적인 요청 흐름은 유지하세요.
- Line 14: Update the cookie configuration in CookieUtil so SameSite=None is
used only when the configured cookie-secure setting is true. For local HTTP
profiles with cookie-secure=false, apply an appropriate non-None SameSite
policy, while preserving the existing secure production behavior.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 02cfe1d3-5d65-43a5-8eb2-fc8a684fcb8b

📥 Commits

Reviewing files that changed from the base of the PR and between 4ce640a and 703cd87.

📒 Files selected for processing (1)
  • src/main/java/com/Timo/Timo/global/auth/utils/CookieUtil.java

Comment thread src/main/java/com/Timo/Timo/global/auth/utils/CookieUtil.java Outdated

@laura-jung laura-jung left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

아 이걸 놓쳤네요 수정감사합니다.

@github-actions github-actions Bot added the slack-approval-notified Slack 승인 완료 알림 중복 방지용 라벨 label Jul 15, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
src/main/java/com/Timo/Timo/global/auth/filter/OriginValidationFilter.java (1)

32-36: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

모바일 앱 등 비브라우저 클라이언트의 Origin 부재로 인한 차단 가능성을 확인해 주세요.

현재 로직은 origin == null일 경우 즉시 403(Forbidden)을 반환하여 차단합니다.
웹 브라우저 환경에서는 SameSite=None 설정에 따른 CSRF 공격을 방어하기 위해 Origin을 필수로 검증하는 것이 매우 안전하고 적절한 조치입니다.

하지만 모바일 앱(iOS, Android)이나 서버 간(S2S) API 호출 등 브라우저가 아닌 클라이언트에서는 기본적으로 Origin 헤더를 전송하지 않습니다. 만약 이 API가 모바일 앱에서도 사용된다면 정상적인 토큰 재발급이나 로그아웃 요청이 차단될 위험이 있습니다. 서비스가 웹 전용인지 확인하시고, 만약 다중 클라이언트를 지원해야 한다면 커스텀 헤더 기반의 검증 등 추가적인 CSRF 방어책을 고려해 보세요.

추가로, allowedFrontendUrls 환경변수 설정 시 끝에 슬래시(/)가 포함되어 있으면 Origin 헤더(끝에 슬래시가 없음)와 일치하지 않아 차단될 수 있으므로 설정 값에 주의가 필요합니다.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/main/java/com/Timo/Timo/global/auth/filter/OriginValidationFilter.java`
around lines 32 - 36, Review OriginValidationFilter’s client support and decide
whether non-browser clients must access these endpoints; if so, do not reject
missing Origin unconditionally, and add an explicitly authenticated alternative
such as the project’s approved custom-header validation while preserving CSRF
protection for browser requests. Also normalize or validate allowedFrontendUrls
entries so trailing slashes do not prevent matching the browser Origin header.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/main/java/com/Timo/Timo/global/config/SecurityConfig.java`:
- Line 74: Add an originValidationFilterRegistration bean in SecurityConfig that
accepts OriginValidationFilter, wraps it in FilterRegistrationBean, and disables
registration with setEnabled(false). Keep the existing
addFilterBefore(originValidationFilter, JwtAuthenticationFilter.class) ordering
unchanged so the filter runs only within the Spring Security chain.

---

Nitpick comments:
In `@src/main/java/com/Timo/Timo/global/auth/filter/OriginValidationFilter.java`:
- Around line 32-36: Review OriginValidationFilter’s client support and decide
whether non-browser clients must access these endpoints; if so, do not reject
missing Origin unconditionally, and add an explicitly authenticated alternative
such as the project’s approved custom-header validation while preserving CSRF
protection for browser requests. Also normalize or validate allowedFrontendUrls
entries so trailing slashes do not prevent matching the browser Origin header.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: b12b1d3f-91f3-4fa0-bcfc-b733f09900a2

📥 Commits

Reviewing files that changed from the base of the PR and between 703cd87 and 8e06063.

📒 Files selected for processing (2)
  • src/main/java/com/Timo/Timo/global/auth/filter/OriginValidationFilter.java
  • src/main/java/com/Timo/Timo/global/config/SecurityConfig.java

Comment thread src/main/java/com/Timo/Timo/global/config/SecurityConfig.java
@Jy000n

Jy000n commented Jul 15, 2026 •

Copy link
Copy Markdown
Member Author
  • 테스트 관련 댓글에 대한 답글로...

스웨거로는 쿠키 확인과 테스트를 어떻게 해야되는지 몰라서 엄청난 끝없는 403 에러(Swagger의 다중 @CookieValue 조합 버그) 끝에 포스트맨으로 토큰 재발급을 받아서 테스트 결과 화면에 올려놨숩니다..

Swagger의 다중 @CookieValue 조합 버그
image

@laura-jung laura-jung left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

굳입니다 머지해봅시다아ㅏ

@Jy000n
Jy000n merged commit 2385877 into develop Jul 15, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🌸 자윤 🚨 hotfix slack-approval-notified Slack 승인 완료 알림 중복 방지용 라벨

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[hotfix] 로그인 이후 토큰 재발급(reissue) 에러

3 participants