[Daily morning study] CORS 개념과 해결 방법
#daily morning study
CORS란?
CORS(Cross-Origin Resource Sharing)는 브라우저가 다른 출처(origin)의 리소스를 요청할 때 적용되는 HTTP 메커니즘이다. 브라우저는 기본적으로 동일 출처 정책(Same-Origin Policy, SOP)을 따르는데, 이 정책은 한 출처에서 불러온 문서나 스크립트가 다른 출처의 리소스와 상호작용하는 것을 제한한다.
출처(Origin) 정의
출처는 세 가지 요소로 구성된다:
| 요소 | 예시 |
|---|---|
| 프로토콜(scheme) | https |
| 호스트(host) | api.example.com |
| 포트(port) | 443 |
https://api.example.com:443과 https://www.example.com:443은 호스트가 달라 다른 출처다. 프로토콜, 호스트, 포트 중 하나라도 다르면 Cross-Origin 요청이 발생한다.
SOP가 없으면 생기는 문제
동일 출처 정책이 없다면:
- 사용자가
evil.com을 방문한다. evil.com의 JS가bank.com/api/transfer에 요청을 보낸다.- 브라우저는
bank.com의 쿠키(세션)를 함께 전송한다. - 사용자가 로그인된 상태라면 공격자가 이 세션을 악용할 수 있다.
이것이 CSRF(Cross-Site Request Forgery) 공격의 핵심이고, SOP가 이를 막는 주요 방어선 중 하나다.
CORS 동작 원리
브라우저는 Cross-Origin 요청을 두 가지 방식으로 처리한다.
1. 단순 요청 (Simple Request)
다음 조건을 모두 만족하는 경우 단순 요청으로 처리된다:
- 메서드:
GET,POST,HEAD중 하나 - 헤더:
Accept,Accept-Language,Content-Language,Content-Type만 사용 Content-Type이application/x-www-form-urlencoded,multipart/form-data,text/plain중 하나
단순 요청은 브라우저가 요청을 바로 보내고, 서버 응답의 Access-Control-Allow-Origin 헤더를 확인해서 허용 여부를 결정한다.
GET /api/data HTTP/1.1
Origin: https://frontend.example.com
HTTP/1.1 200 OK
Access-Control-Allow-Origin: https://frontend.example.com
2. 사전 요청 (Preflight Request)
단순 요청 조건을 만족하지 않으면, 브라우저는 실제 요청 전에 OPTIONS 메서드로 사전 요청을 먼저 보낸다.
OPTIONS /api/data HTTP/1.1
Origin: https://frontend.example.com
Access-Control-Request-Method: PUT
Access-Control-Request-Headers: Content-Type, Authorization
HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://frontend.example.com
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Max-Age: 86400
Access-Control-Max-Age는 Preflight 결과를 캐시할 시간(초)이다. 설정하면 매 요청마다 Preflight를 반복하지 않아도 된다.
CORS 관련 주요 헤더
응답 헤더 (서버 → 브라우저)
| 헤더 | 설명 |
|---|---|
Access-Control-Allow-Origin | 허용할 출처. * 또는 특정 도메인 |
Access-Control-Allow-Methods | 허용할 HTTP 메서드 목록 |
Access-Control-Allow-Headers | 허용할 요청 헤더 목록 |
Access-Control-Allow-Credentials | 쿠키/인증 정보 포함 여부 |
Access-Control-Expose-Headers | JS에서 접근 가능한 응답 헤더 목록 |
Access-Control-Max-Age | Preflight 캐시 유효 시간 |
요청 헤더 (브라우저 → 서버)
| 헤더 | 설명 |
|---|---|
Origin | 요청 출처 |
Access-Control-Request-Method | Preflight 시 실제 메서드 |
Access-Control-Request-Headers | Preflight 시 실제 헤더 목록 |
Credentials 포함 요청
쿠키나 Authorization 헤더 같은 인증 정보를 Cross-Origin 요청에 포함하려면 별도 설정이 필요하다.
클라이언트 (fetch API)
fetch('https://api.example.com/data', {
credentials: 'include' // 쿠키 포함
});
서버 응답
Access-Control-Allow-Origin: https://frontend.example.com
Access-Control-Allow-Credentials: true
이때 Access-Control-Allow-Origin에 *(와일드카드)는 사용할 수 없다. 반드시 특정 출처를 명시해야 한다.
서버별 CORS 설정 방법
Express.js (Node.js)
const cors = require('cors');
app.use(cors({
origin: 'https://frontend.example.com',
methods: ['GET', 'POST', 'PUT', 'DELETE'],
allowedHeaders: ['Content-Type', 'Authorization'],
credentials: true,
}));
여러 출처를 허용하려면:
const allowedOrigins = ['https://app.example.com', 'https://admin.example.com'];
app.use(cors({
origin: (origin, callback) => {
if (!origin || allowedOrigins.includes(origin)) {
callback(null, true);
} else {
callback(new Error('Not allowed by CORS'));
}
},
}));
Spring Boot (Java)
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("https://frontend.example.com")
.allowedMethods("GET", "POST", "PUT", "DELETE")
.allowedHeaders("*")
.allowCredentials(true)
.maxAge(3600);
}
}
Nginx 프록시 레벨 설정
location /api/ {
add_header 'Access-Control-Allow-Origin' 'https://frontend.example.com' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS' always;
add_header 'Access-Control-Allow-Headers' 'Authorization, Content-Type' always;
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Max-Age' 86400;
return 204;
}
proxy_pass http://backend;
}
개발 환경에서의 CORS 우회
로컬 개발 중에는 프론트엔드(localhost:3000)와 백엔드(localhost:8080)가 포트가 달라 CORS 에러가 자주 발생한다.
Vite / Webpack Dev Server 프록시 설정
// vite.config.js
export default {
server: {
proxy: {
'/api': {
target: 'http://localhost:8080',
changeOrigin: true,
}
}
}
}
이 방식은 브라우저가 /api/...를 localhost:3000/api/...로 요청하고, 개발 서버가 localhost:8080으로 프록시한다. 브라우저 입장에서는 같은 출처로 보여 CORS 문제가 없다.
CORS 에러 디버깅
CORS 에러는 브라우저 콘솔에서 확인할 수 있다:
Access to fetch at 'https://api.example.com/data' from origin
'https://frontend.example.com' has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
체크리스트:
- 서버 응답에
Access-Control-Allow-Origin헤더가 있는가? - 헤더의 값이 요청
Origin과 일치하는가? - Preflight 요청(
OPTIONS)에도 올바른 헤더가 반환되는가? - Credentials 요청인 경우 와일드카드
*를 사용하지 않았는가? - HTTPS → HTTP 요청은 Mixed Content 정책으로 차단될 수 있음
CORS vs CSRF
혼동하기 쉬운 두 개념의 차이:
| 구분 | CORS | CSRF |
|---|---|---|
| 목적 | Cross-Origin 리소스 접근 제어 | Cross-Site 요청 위조 방어 |
| 동작 주체 | 브라우저 | 공격자의 웹사이트 |
| 방어 방법 | 서버의 CORS 헤더 설정 | CSRF 토큰, SameSite 쿠키 |
| SOP와 관계 | SOP 완화 메커니즘 | SOP 우회 공격 |
CORS는 SOP를 선택적으로 완화하는 메커니즘이고, CSRF는 SOP가 커버하지 못하는 취약점을 노리는 공격이다. 쿠키는 SOP와 무관하게 자동으로 전송되기 때문에 CSRF가 발생할 수 있다.