CORS란 무엇인가?
CORS(Cross-Origin Resource Sharing)는 웹 브라우저의 보안 정책 중 하나로, 서로 다른 출처(Origin) 간의 리소스 요청을 제한하는 기능입니다. 즉, 클라이언트(예: React)와 서버(예: Spring Boot)가 다른 도메인에서 실행될 경우, 브라우저는 보안상의 이유로 기본적으로 요청을 차단합니다.
예를 들어, http://localhost:9000에서 실행 중인 프론트엔드가 http://localhost:8080의 API를 호출하면 CORS 정책에 의해 차단될 수 있습니다.
대표적인 CORS 오류 메시지
Access to fetch at 'http://localhost:8080/api/data' from origin 'http://localhost:9000'
has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
스프링 부트에서 CORS 해결 방법
1. WebMvcConfigurer 설정하기 (권장)
Spring Boot에서는 WebMvcConfigurer 인터페이스를 구현하여 CORS 정책을 설정할 수 있습니다.
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("/**") // 모든 경로에 대해 CORS 허용
.allowedOrigins("http://localhost:9000") // 허용할 오리진 설정
.allowedMethods("GET", "POST", "PUT", "DELETE") // 허용할 HTTP 메서드 지정
.allowedHeaders("*") // 모든 헤더 허용
.allowCredentials(true) // 쿠키 허용
.maxAge(3600); // 캐시 시간 (초)
}
}
장점: 설정이 간단하고, Spring Security와도 쉽게 연동할 수 있음.
2. @CrossOrigin 어노테이션 사용하기 (컨트롤러별 적용)
각각의 컨트롤러 혹은 특정 API 메서드에 대해 CORS 설정을 적용할 수도 있습니다.
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")
@CrossOrigin(origins = "http://localhost:9000") // 특정 오리진 허용
public class MyController {
@GetMapping("/data")
public String getData() {
return "CORS 요청 성공!";
}
}
장점: 특정 API 엔드포인트만 CORS 허용하고 싶을 때 유용함.
3. CorsFilter를 사용한 설정 (필터 방식, 확장 가능)
Spring Boot의 필터를 직접 구현하여 CORS 정책을 설정할 수도 있습니다.
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@Configuration
public class CorsConfig {
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("http://localhost:9000"); // 허용할 오리진
config.addAllowedHeader("*");
config.addAllowedMethod("*"); // 모든 HTTP 메서드 허용
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
}
장점: 필요에 따라 동적으로 CORS 정책을 변경할 때 유용함.
정리
스프링 부트에서 CORS 문제를 해결하는 방법은 여러 가지가 있으며, 가장 일반적으로는 WebMvcConfigurer 방식이 추천됩니다. 특정 컨트롤러에만 적용할 경우 @CrossOrigin을, 보다 유연한 정책을 적용하려면 CorsFilter를 사용할 수 있습니다.
'Back-End > Java & Spring' 카테고리의 다른 글
Ubuntu에서 Spring Boot 애플리케이션 배포하기 – Git, Gradle, Tomcat을 활용 (0) | 2025.02.20 |
---|---|
Spring Boot에서 Bean Scope 설정하기 (0) | 2025.02.18 |
H2 Database 설정하기(feat.Spring Boot) (0) | 2025.02.18 |