Skip to content

fix: 프론트 연동 시 CORS 설정 추가로 preflight 차단(403) 해결 - #37

Merged
yxpjseo merged 1 commit into
developfrom
fix/cors-config
Aug 3, 2026
Merged

yxpjseo merged 1 commit into
developfrom
fix/cors-config

Conversation

@yxpjseo

@yxpjseo yxpjseo commented Aug 1, 2026 •

Copy link
Copy Markdown
Collaborator

📌 관련 이슈

  • close #00

🔎 What is this PR?

SecurityConfig에 CORS 설정이 없어 브라우저의 preflight(OPTIONS) 응답에 Access-Control-Allow-Origin 헤더가 붙지 않아 프론트 연동 요청이 차단되는 문제 해결

✨ Changes

.cors() 활성화 및 CorsConfigurationSource 빈 추가

📷 Result


💬 To. Reviewer


✅ 체크 리스트

  • base 브랜치(develop 또는 main) 최신 상태 pull 및 충돌 확인 완료
  • Reviewers 설정
  • Assignees 설정
  • Labels 설정

Summary by CodeRabbit

  • Bug Fixes
    • Improved cross-origin access for supported application requests.
    • Enabled standard HTTP methods and headers, credentialed requests, and smoother browser preflight handling.

@yxpjseo yxpjseo self-assigned this Aug 1, 2026
@yxpjseo yxpjseo added the 🐛 fix develop 브랜치에서 발생한 버그를 수정하는 작업 label Aug 1, 2026
@coderabbitai

coderabbitai Bot commented Aug 1, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: f4c669c7-73d4-47e1-84da-b57b0664f1e5

📥 Commits

Reviewing files that changed from the base of the PR and between 44e8e2b and f65a025.

📒 Files selected for processing (1)
  • src/main/java/com/daytodo/global/config/SecurityConfig.java

📝 Walkthrough

Walkthrough

SecurityConfig enables CORS in the security filter chain. A new configuration source permits credentialed requests from all origin patterns, common methods, all headers, and one-hour preflight caching.

Changes

CORS security integration

Layer / File(s) Summary
Configure CORS in the security filter chain
src/main/java/com/daytodo/global/config/SecurityConfig.java
The security filter chain uses corsConfigurationSource(). The new bean configures credentialed requests, allowed methods, all headers, one-hour preflight caching, and all request paths.

Estimated code review effort: 2 (Simple) | ~10 minutes

Suggested reviewers: hyeoniss

🚥 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 The title clearly identifies the CORS configuration change and the resulting preflight 403 fix.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/cors-config

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.

@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

🤖 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/daytodo/global/config/SecurityConfig.java`:
- Around line 92-97: Update the CORS configuration in SecurityConfig to use the
configured trusted frontend origins instead of List.of("*"), while retaining
only the methods and headers required by the application. Keep allowCredentials
enabled only if the configured authentication flow requires it, and remove or
update the conflicting Access-Control-Allow-Origin wildcard in nginx
configuration.
🪄 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: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: da32de97-2fbb-41f3-8d4e-338a643aff3e

📥 Commits

Reviewing files that changed from the base of the PR and between b4ca263 and 959d190.

📒 Files selected for processing (1)
  • src/main/java/com/daytodo/global/config/SecurityConfig.java

Comment on lines +92 to +97
// allowCredentials(true)라 "*"는 못 쓰고 패턴을 사용 - 요청 Origin을 그대로 반사한다.
// TODO(팀 확인 필요): 배포 안정화되면 프론트 도메인만 명시적으로 화이트리스트할 것.
config.setAllowedOriginPatterns(List.of("*"));
config.setAllowedMethods(List.of("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"));
config.setAllowedHeaders(List.of("*"));
config.setAllowCredentials(true);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔒 Security & Privacy | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

echo "CORS origins and configuration:"
fd --type f --hidden --exclude .git -0 \
  | xargs -0 -r rg -n \
    'setAllowedOrigin|setAllowedOriginPattern|allowed-origin|allowedOrigin|https?://' || true

echo "Authentication transport:"
fd --type f --hidden --exclude .git -0 \
  | xargs -0 -r rg -n \
    'Cookie|ResponseCookie|setCookie|Authorization|Bearer|localStorage|sessionStorage' || true

if rg -n --glob '*.java' \
  'setAllowedOriginPatterns\(List\.of\("\*"\)\)' .; then
  echo "Wildcard CORS origin remains." >&2
  exit 1
fi

Repository: DayTodo/DayTodo_BE

Length of output: 1935


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

echo "Security configuration:"
sed -n '1,140p' src/main/java/com/daytodo/global/config/SecurityConfig.java

echo "JWT filter:"
sed -n '1,180p' src/main/java/com/daytodo/global/security/JwtAuthenticationFilter.java

echo "Authentication and token transport references:"
rg -n -C 3 \
  'JwtAuthenticationFilter|Authorization|Bearer|HttpOnly|SameSite|Cookie|ResponseCookie|Set-Cookie|accessToken|refreshToken|oauth2|login' \
  src/main/java src/main/resources .platform || true

echo "Relevant configuration:"
sed -n '1,120p' src/main/resources/application.yml
sed -n '1,100p' .platform/ngnix.conf

Repository: DayTodo/DayTodo_BE

Length of output: 28259


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

python3 - <<'PY'
from pathlib import Path
import re

root = Path(".")
java = list(root.glob("src/main/java/**/*.java"))
text = "\n".join(p.read_text(errors="ignore") for p in java)

patterns = {
    "cookie APIs": r"\b(?:Cookie|ResponseCookie|HttpCookie|Set-Cookie|addCookie)\b",
    "authorization header": r"HttpHeaders\.AUTHORIZATION|Authorization",
    "bearer parsing": r"Bearer\s*\+?|BEARER_PREFIX|startsWith\([^)]*Bearer",
    "CORS wildcard": r"setAllowedOriginPatterns\s*\(\s*List\.of\(\s*\"\*\"\s*\)\s*\)",
}
for label, pattern in patterns.items():
    matches = [(str(p), i + 1, line.strip())
               for p in java
               for i, line in enumerate(p.read_text(errors="ignore").splitlines())
               if re.search(pattern, line, re.I)]
    print(f"{label}: {len(matches)}")
    for item in matches:
        print("  ", item)
PY

Repository: DayTodo/DayTodo_BE

Length of output: 1390


Restrict CORS to trusted frontend origins.

The application reads JWTs only from the Authorization header and does not use cookies, so this wildcard does not currently expose authenticated JWT responses by itself. Replace List.of("*") with configured frontend origins, and remove or update .platform/ngnix.conf because it also sets Access-Control-Allow-Origin: '*'. Keep credentials enabled only when required.

🧰 Tools
🪛 ast-grep (0.45.0)

[warning] 93-93: This 'CorsConfiguration' allows requests from any origin (""). A wildcard origin combined with credentials (or used at all on authenticated endpoints) lets any website read responses from this service. Configure an explicit allow-list instead, e.g. 'config.setAllowedOrigins(List.of("https://app.example.com"));', and avoid pairing wildcard origins with 'setAllowCredentials(true)'.
Context: config.setAllowedOriginPatterns(List.of("
"))
Note: [CWE-942] Permissive Cross-domain Policy with Untrusted Domains.

(cors-allow-all-origins-config-java)

🤖 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/daytodo/global/config/SecurityConfig.java` around lines 92
- 97, Update the CORS configuration in SecurityConfig to use the configured
trusted frontend origins instead of List.of("*"), while retaining only the
methods and headers required by the application. Keep allowCredentials enabled
only if the configured authentication flow requires it, and remove or update the
conflicting Access-Control-Allow-Origin wildcard in nginx configuration.

Source: Linters/SAST tools

kwonwnsduf
kwonwnsduf previously approved these changes Aug 3, 2026

@kwonwnsduf kwonwnsduf 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.

수고하셨습니다

SecurityConfig에 CORS 설정이 없어 브라우저의 preflight(OPTIONS) 응답에
Access-Control-Allow-Origin 헤더가 붙지 않아 프론트 연동 요청이 차단됨.
.cors() 활성화 및 CorsConfigurationSource 빈 추가.
@yxpjseo
yxpjseo merged commit 716c0b8 into develop Aug 3, 2026
1 check passed
@yxpjseo
yxpjseo deleted the fix/cors-config branch August 3, 2026 09:06
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐛 fix develop 브랜치에서 발생한 버그를 수정하는 작업

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants