목차
- 서문
- CORS 오류의 원인과 동작 원리
- Spring Boot에서의 CORS 해결 방법 3가지
- Spring Boot CORS 주요 설정 옵션 비교
- 실무 트러블슈팅 및 주의사항
- 자주 묻는 질문 (FAQ)
- 환경 및 참고 안내
서문
프론트엔드(React, Vue, Angular 등) 애플리케이션과 백엔드 Spring Boot API 서버를 분리하여 개발할 때 개발자가 가장 흔하게 접하는 장애 중 하나가 바로 CORS(Cross-Origin Resource Sharing) 에러입니다. 웹 브라우저는 보안상의 이유로 기본적으로 출처(Origin)가 다른 리소스 요청을 제한하며, 서버 측에서 명시적으로 허용 방침을 응답 헤더에 담아 전달해야만 정상적인 데이터 수신이 가능합니다. 이 글에서는 CORS의 근본적인 발생 원인과 Preflight 요청의 동작 메커니즘을 살펴보고, Spring Boot 환경에서 상황에 맞게 CORS 설정을 적용하는 3가지 실무 방식을 코드 예제와 함께 자세히 다룹니다.
CORS 오류의 원인과 동작 원리
CORS 오류를 제대로 해결하기 위해서는 먼저 브라우저의 기본 보안 정책인 SOP(Same-Origin Policy, 동일 출처 정책)를 이해해야 합니다.
1. SOP(Same-Origin Policy)란?
SOP는 어떤 출처(Origin)에서 불러온 문서나 스크립트가 다른 출처의 리소스와 상호작용하는 것을 제한하는 중요한 보안 메커니즘입니다. 여기서 출처(Origin)는 Protocol(프로토콜), Host(도메인), Port(포트번호) 3가지 요소의 조합으로 정의됩니다.
https://example.com:443/api/v1/users- Protocol:
https:// - Host:
example.com - Port:
443
- Protocol:
위 3가지 항목 중 하나라도 다르면 브라우저는 이를 ‘다른 출처(Cross-Origin)’로 인식합니다. 예를 들어, 프론트엔드가 http://localhost:3000에서 실행 중이고 백엔드 API가 http://localhost:8080에서 실행 중이라면 포트 번호가 다르므로 Cross-Origin 요청이 됩니다.
2. CORS(Cross-Origin Resource Sharing)와 Preflight 요청
CORS는 SOP 정책의 예외를 허용하기 위해 웹 브라우저와 서버가 HTTP 헤더를 통해 협상하는 표준 방식입니다. 브라우저는 보안 위험이 있는 Cross-Origin 요청을 보낼 때 실제 요청을 전송하기 전 Preflight(사전 요청)을 먼저 전송합니다.
[Browser] --- OPTIONS (Preflight Request) ---> [Spring Boot Server]
<--- 200 OK (Access-Control-*) ------
[Browser] --- GET/POST (Actual Request) ------> [Spring Boot Server]
<--- 200 OK (Data Payload) ---------
Preflight 요청은 OPTIONS HTTP 메서드를 사용하며, 서버가 해당 요청의 Origin, Method, Header를 허용하는지 검증합니다. 서버 응답에 적절한 Access-Control-Allow-Origin 헤더가 포함되어 있지 않으면 브라우저는 보안 위반으로 판단하여 스크립트 수준에서 응답 데이터 수신을 차단하고 콘솔에 CORS 에러를 출력합니다.
Spring Boot에서의 CORS 해결 방법 3가지
Spring Boot에서는 애플리케이션의 규모와 보안 요구사항(Spring Security 적용 여부 등)에 따라 크게 3가지 방식으로 CORS를 설정할 수 있습니다.
방법 1. @CrossOrigin 어노테이션 사용 (특정 Controller/Method 단위)
가장 간단한 방법으로, 컨트롤러 클래스 상단이나 특정 RequestMapping 메서드에 @CrossOrigin 어노테이션을 부착합니다.
package com.example.demo.controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/v1/products")
// 특정 Origin 및 허용 HTTP 메서드 지정
@CrossOrigin(origins = "http://localhost:3000", allowedHeaders = "*", maxAge = 3600)
public class ProductController {
@GetMapping
public String getProducts() {
return "Product List Data";
}
}
- 장점: 설정이 직관적이며 특정 엔드포인트에 대해서만 예외적으로 CORS를 허용할 때 유용합니다.
- 단점: 컨트롤러 수가 늘어날 경우 코드 중복이 발생하고 전체 애플리케이션 차원의 일관된 관리 및 변경이 어렵습니다.
방법 2. WebMvcConfigurer를 이용한 글로벌 설정 (Global Policy)
Spring MVC 전체 컨트롤러 경로에 대해 일괄적으로 CORS 정책을 적용하는 가장 권장되는 글로벌 방식입니다.
package com.example.demo.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**") // CORS를 적용할 URL 패턴 정의
.allowedOriginPatterns("http://localhost:3000", "https://*.mydomain.com") // 허용할 Origin (패턴 지원)
.allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS") // 허용할 HTTP 메서드
.allowedHeaders("*") // 허용할 Request Header
.allowCredentials(true) // 쿠키 및 인증 헤더 허용 여부
.maxAge(3600); // Preflight 요청 캐싱 시간(초)
}
}
- 장점: 중앙 집중식으로 전체 엔드포인트의 CORS 정책을 일관성 있게 관리할 수 있습니다.
- 주의: Spring Security를 사용하는 경우, Spring MVC 인터셉터 단계 이전에 위치한 Security Filter Chain에서 Preflight 요청이 차단될 수 있으므로 아래의 방법 3을 적용해야 합니다.
방법 3. CorsFilter 및 Spring Security 통합 설정
Spring Security가 프로젝트에 포함되어 있다면, Security Filter Chain 내에서 Preflight 요청을 가장 먼저 처리할 수 있도록 CorsConfigurationSource를 Security 설정 Bean으로 등록해야 합니다.
package com.example.demo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import java.util.List;
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
// Spring Security 필터 체인에 CORS 설정 적용
.cors(cors -> cors.configurationSource(corsConfigurationSource()))
.csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/public/**").permitAll()
.anyRequest().authenticated()
);
return http.build();
}
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
// 인증 정보를 포함한 요청(Cookie/Authorization Header) 허용 시 특정 Origin 패턴 지정 필수
configuration.setAllowedOriginPatterns(List.of("http://localhost:3000", "https://*.mydomain.com"));
configuration.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"));
configuration.setAllowedHeaders(List.of("*"));
configuration.setExposedHeaders(List.of("Authorization", "Set-Cookie")); // 클라이언트 JS가 읽을 수 있는 Header
configuration.setAllowCredentials(true);
configuration.setMaxAge(3600L);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
Spring Boot CORS 주요 설정 옵션 비교
CORS 설정 시 빈번하게 사용되는 주요 메소드와 설정 옵션의 차이점 및 주의사항입니다.
| 설정 메서드 / 옵션 | 주요 설명 | 보안 권장사항 및 주의사항 |
|---|---|---|
allowedOrigins("*") | 모든 Origin에서의 리소스 요청을 허용함 | allowCredentials(true) 설정 시 함께 사용할 경우 예외 발생 |
allowedOriginPatterns(...) | 와일드카드(*)가 포함된 와일드카드 도메인 패턴 허용 | allowCredentials(true) 사용 시 allowedOrigins 대신 권장 |
allowedMethods(...) | 허용할 HTTP 메서드 명시 (GET, POST, OPTIONS 등) | RESTful API 구축 시 OPTIONS 메서드가 누락되지 않도록 주의 |
allowedHeaders(...) | 클라이언트가 요청 시 전송할 수 있는 HTTP Header 명시 | 커스텀 헤더(예: X-AUTH-TOKEN)를 사용하는 경우 명시 필요 |
exposedHeaders(...) | 브라우저 스크립트(JS)에서 접근 허용할 Response Header | JWT 토큰 등을 Response Header로 전달할 때 반드시 등록 필요 |
allowCredentials(boolean) | 자격 증명(Cookie, Authorization Header 등) 허용 여부 | true 설정 시 allowedOrigins("*") 절대 사용 불가 |
maxAge(long seconds) | Preflight 요청 결과를 브라우저가 캐싱할 시간 설정 | 불필요한 Preflight OPTIONS 요청 재발송을 줄여 성능 향상 |
실무 트러블슈팅 및 주의사항
1. allowCredentials(true) 설정 시 allowedOrigins("*") 예외 발생
Spring Framework 5.3 / Spring Boot 2.4 이후 버전부터는 보안 규격 강화로 인해 allowCredentials(true)와 allowedOrigins("*")를 동시에 설정할 수 없습니다. 이 경우 애플리케이션 실행 시점 또는 브라우저 요청 시점에 IllegalArgumentException 오류가 발생합니다.
- 해결책:
allowedOrigins("*")대신allowedOriginPatterns("http://localhost:3000", "https://*.domain.com")을 사용하여 와일드카드 패턴을 지정해야 합니다.
2. Spring Security 사용 시 MVC 설정만 적용한 경우
WebMvcConfigurer를 이용해 CORS를 설정했음에도 불구하고 Spring Security가 적용되어 있다면, Security Filter가 MVC DispatcherServlet보다 먼저 실행되므로 Preflight(OPTIONS) 요청이 401 Unauthorized 또는 403 Forbidden 응답으로 차단될 수 있습니다.
- 해결책: 반드시
SecurityFilterChainBean 설정 내에http.cors(cors -> cors.configurationSource(...))를 포함시키거나CorsFilter를 Security Filter Chain의 최우선 순위(ChannelProcessingFilter전)로 등록해야 합니다.
3. 커스텀 응답 헤더가 클라이언트 JS에서 조회되지 않는 현상
서버 응답 헤더에 Authorization 토큰이나 사용자 정의 헤더를 담아서 전송하더라도, CORS 정책상 브라우저는 기본적으로 6가지 기본 헤더(Cache-Control, Content-Language, Content-Type, Expires, Last-Modified, Pragma)만 스크립트에 노출합니다.
- 해결책:
configuration.setExposedHeaders(List.of("Authorization", "Custom-Header"))와 같이 클라이언트가 읽어야 하는 헤더를 명시적으로 노출 설정해야 합니다.
자주 묻는 질문 (FAQ)
Q1. Local 환경에서는 잘 작동하다가 운영(Production) 환경에서만 CORS 오류가 발생합니다. 원인이 무엇인가요?
A1. 운영 환경에서는 Nginx, AWS ALB, Cloudfront와 같은 Reverse Proxy 또는 API Gateway가 백엔드 앞단에 위치하는 경우가 많습니다. Proxy 서버에서 CORS 헤더를 중복하여 추가하거나, Nginx 레벨에서 OPTIONS 메서드 요청을 차단(405 Method Not Allowed)하고 있지 않은지 확인해야 합니다. 중복된 Access-Control-Allow-Origin 헤더가 전달되어도 브라우저는 CORS 에러를 발생시킵니다.
Q2. Preflight 요청의 Caching 시간을 설정하는 maxAge의 권장 값은 얼마인가요?
A2. 서비스의 특성에 따라 다르지만 보통 3600(1시간)을 권장합니다. 크롬 브라우저의 경우 자체적인 보안 규격으로 인해 maxAge를 최대 7200초(2시간), Firefox는 24시간(86400초)까지 허용합니다. 적절한 Caching 시간을 부여하면 불필요한 Preflight OPTIONS RTT(Round Trip Time) 비용을 크게 줄일 수 있습니다.
환경 및 참고 안내
본 포스팅의 코드와 설정 예제는 Spring Boot 3.x 및 Spring Security 6.x 버전(JDK 17 이상)을 기준으로 검증되었으며, 사용 중인 프레임워크·런타임 버전에 따라 일부 옵션이나 메서드 시그니처가 달라질 수 있으므로 공식 Spring Reference 문서를 함께 참고하시기 바랍니다.








