import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@SpringBootConfiguration
public class WebGlobalConfig {
@Bean
public CorsFilter corsFilter() {
//CorsConfiguration 개체 생성 후 설정 추가
CorsConfiguration config = new CorsConfiguration();
//내보낼 원본 도메인 설정
config.addAllowedOrigin("*");
//원본 요청 헤더 정보 내보내기
config.addAllowedHeader("*");
//header 의 노출 정보
config.addExposedHeader("*");
//허용할 요청 항목들
config.addAllowedMethod("GET"); //get
config.addAllowedMethod("PUT"); //put
config.addAllowedMethod("POST"); //post
config.addAllowedMethod("DELETE"); //delete
//corsConfig.addAllowedMethod("*"); //모두허용
// Cookie 전송여부
config.setAllowCredentials(true);
//2. 매핑 경로 추가
UrlBasedCorsConfigurationSource corsConfigurationSource =
new UrlBasedCorsConfigurationSource();
corsConfigurationSource.registerCorsConfiguration("/**", config);
return new CorsFilter(corsConfigurationSource);
}
}
SpringBoot2.4.4 이후 버전사용시 아래 에러 나올수 있음.
java.lang.IllegalArgumentException: When allowCredentials is true, allowedOrigins cannot contain the special value "*" since that cannot be set on the "Access-Control-Allow-Origin" response header. To allow credentials to a set of origins, list them explicitly or consider using "allowedOriginPatterns" instead.
at org.springframework.web.cors.CorsConfiguration.validateAllowCredentials(CorsConfiguration.java:453) ~[spring-web-5.3.6.jar:5.3.6]
allow Credentials가 true일 때 alloed Origins는 이 값을 'Access-Control-Allow-Origin' 응답 헤드에서 설정할 수 없기 때문에 특수 값 '*'를 포함할 수 없음. 인증 정보 액세스를 허용하려면 소스를 명시적으로 나열하거나 'Allowed Origin Patterns'로 변경.
해결방법: config.addAllowedOrigin("*"); --> config.addAllowedOriginPattern("*"); 로 변경.
WebMvcConfigurer 재정의하는 방법
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@SpringBootConfiguration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
//매핑경로 추가
registry.addMapping("/**")
//Cookie 전송여부
.allowCredentials(true)
//내보낼 원본 도메인 설정 SpringBoot2.4.4 이하 버전은 .allowedOrigins("*") 사용.
.allowedOriginPatterns("*")
//요청 방식을 허용
.allowedMethods(new String[]{"GET", "POST", "PUT", "DELETE"})
//.allowedMethods("*") //요청 방식을 전부 허용
//원본 요청 헤더 정보 내보내기
.allowedHeaders("*")
//원본 요청 헤더 정보 노출
.exposedHeaders("*");
}
}