CORS 설정
http
.cors((corsCustomizer -> corsCustomizer.configurationSource(new CorsConfigurationSource() {
@Override
public CorsConfiguration getCorsConfiguration(HttpServletRequest request) {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Collections.singletonList("http://localhost:3000"));
configuration.setAllowedMethods(Collections.singletonList("*"));
configuration.setAllowCredentials(true);
configuration.setAllowedHeaders(Collections.singletonList("*"));
configuration.setMaxAge(3600L);
configuration.setExposedHeaders(Collections.singletonList("Authorization"));
return configuration;
}
})));
CORS ?
- 한 도메인에서 실행되는 웹 애플리케이션이 다른 도메인의 자원에 접근할 수 있도록 허용하는 메커니즘
- 예로 프론트는 localhost:3000에서 실행되고 백엔드는 8080에서 실행되는 경우
CORS를 설정하지 않으면 프론트에서 백으로 API 요청을 보낼 때 브라우저가 CORS 에러를 발생시킵니다
- 따라서, CORS 설정은 웹 애플리케이션에서 클라이언트와 서버 간의 자원 공유를 허용하기 위한 설정
CorsMvcConfig 생성
@Configuration
public class CorsMvcConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry corsRegistry) {
corsRegistry.addMapping("/**")
.allowedOrigins("http://localhost:3000");
}
}
Spring MVC의 CORS 설정
- addCorsMappings 메서드를 사용
- Security Filter Chain에 걸리지 않는 요청에도 CORS 정책을 적용할 수 있음
왜 두 개를 함께 설정해야하냐!?
- http.cors() 설정은 Spring Security의 필터가 적용되는 API 요청에 대해서만 동작하고 WebMvcConfigurer의 addCorsMappings 설정은 Spring Security를 거치지 않는 요청에도 CORS를 적용한다
즉, 확실하게 하려고 ㅎ_ㅎ