3.10 CORS 설정
브라우저는 다른 출처(Origin) 의 API를 호출할 때 Same-Origin Policy로 인해 기본적으로 차단합니다. 프론트가 https://front.com이고 API가 https://api.com이면 CORS(Cross-Origin Resource Sharing) 헤더를 서버에서 보내줘야 합니다.
작성 기준: Spring Boot 3.2.x
1. CORS란?
- Origin: 프로토콜 + 호스트 + 포트 (예:
https://front.com:443) - 브라우저가 preflight(OPTIONS) 요청을 보내고, 서버가 Access-Control-Allow-Origin 등으로 “이 출처 허용”을 알려주면 실제 요청을 진행합니다.
2. 전역 설정 (WebMvcConfigurer)
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("https://front.example.com", "http://localhost:3000")
.allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS")
.allowedHeaders("*")
.allowCredentials(true)
.maxAge(3600);
}
}
- addMapping: 적용할 경로 패턴
- allowedOrigins: 허용할 출처.
*와 allowCredentials(true) 는 동시에 사용 불가 - allowedMethods: 허용 HTTP 메서드
- allowedHeaders: 허용 요청 헤더.
*또는 나열 - allowCredentials: 쿠키·인증 정보 포함 허용
- maxAge: preflight 응답 캐시 시간(초)
3. Spring Security와 함께 사용
Security를 쓰면 CorsConfigurationSource 빈으로 CORS를 설정하는 편이 명확합니다.
@Configuration
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.cors(cors -> cors.configurationSource(corsConfigurationSource()))
.authorizeHttpRequests(auth -> auth.anyRequest().authenticated());
return http.build();
}
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration config = new CorsConfiguration();
config.setAllowedOrigins(List.of("https://front.example.com"));
config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "OPTIONS"));
config.setAllowedHeaders(List.of("*"));
config.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/api/**", config);
return source;
}
}
4. 메서드/컨트롤러 단위 (@CrossOrigin)
특정 API만 허용할 때 @CrossOrigin을 사용할 수 있습니다.
@RestController
@RequestMapping("/api/public")
@CrossOrigin(origins = "https://front.example.com", maxAge = 3600)
public class PublicController { ... }
- 전역 설정과 겹치면 합쳐진다고 보면 됩니다. 운영에서는 전역 설정으로 통일하는 경우가 많습니다.
팁
운영 환경에서는 allowedOrigins를 구체적인 도메인으로 제한하고, *와 allowCredentials(true) 를 동시에 쓰지 않도록 하세요.