CORS, 즉 Cross-Origin Resource Sharing,는 웹페이지가 다른 도메인의 리소스에 접근할 수 있도록 허용하는 메커니즘이다. 기본적으로, 웹 브라우저는 보안상의 이유로 "동일 출처 정책(Same-Origin Policy)"을 적용한다. 이 정책은 한 출처(origin)에서 로드된 문서나 스크립트가 다른 출처의 리소스와 상호작용하는 것을 제한한다.
CORS는 이러한 제한을 완화할 수 있는 방법을 제공한다. 웹 애플리케이션은 HTTP 헤더를 사용하여 다른 출처의 리소스에 대한 접근을 허용할 수 있다. 예를 들어, 웹 서버는 Access-Control-Allow-Origin이라는 HTTP 헤더를 사용하여 특정 출처의 요청을 수락하거나 모든 출처의 요청을 허용할 수 있다.
Spring Boot를 사용하여 백엔드 서버에서 CORS를 허용
@CrossOrigin 어노테이션 사용
이 방법은 특정 컨트롤러 또는 메소드에만 CORS를 적용할 때 유용하다.
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
@CrossOrigin(origins = "http://example.com")
@GetMapping("/myEndpoint")
public String myMethod() {
// ...
}
}
전역 CORS
WebMvcConfigurer 인터페이스를 구현하여 addCorsMappings 메서드를 오버라이드함으로써 CORS 설정을 적용할 수 있다. 이 방법은 Spring Boot 애플리케이션에서 전역 CORS 설정을 적용하는 데 자주 사용되며, 모든 컨트롤러와 핸들러 메소드에 대한 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("/**")
.allowedOrigins("http://example.com")
.allowedMethods("GET", "POST", "PUT", "DELETE")
.allowedHeaders("*")
.allowCredentials(true);
}
}
CORS 필터 사용
Spring Boot에서 제공하는 CorsFilter를 사용하여 CORS 설정을 할 수 있다. 이 방법은 더 세밀한 설정이 필요할 때 유용하다.
import org.springframework.boot.web.servlet.FilterRegistrationBean;
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 MyFilterConfig {
@Bean
public FilterRegistrationBean<CorsFilter> customCorsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("http://example.com");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<>(new CorsFilter(source));
bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
return bean;
}
}