Springboot 3가지 CROS 설정

총3가지 방법 요약

CorsFilter 설정

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 재정의하는 방법

@CrossOrigin 어노테이션으로 부분적용

이후 사용되는 모든 controller 에 @CrossOrigin 붙여준다.

혹은 사용되는 각각의 메소드에 붙여줘도 된다.

끝!

Last updated