본문으로 건너뛰기

Spring Boot에서 CORS 설정 시 addCorsMappings 에러

2024년 9월 28일에 작성되었고, 블로그를 이전하며 옮겨온 포스트입니다.
여기에서 원본을 확인할 수 있습니다.

무슨 오류가 발생했을까?

Spring Boot에서 CORS 설정을 하는 도중 다음과 같은 에러가 발생했다.

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.

기존 SecurityConfiguration.java의 코드는 다음과 같다.

@Bean
CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration config = new CorsConfiguration();
    config.addAllowedOrigin("*");
    config.addAllowedHeader("*");
    config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"));
    config.addExposedHeader("Authorization");
    config.addExposedHeader("Authorization-refresh");
    config.addExposedHeader("Set-Cookie");
    config.setAllowCredentials(true);

    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", config);
    return source;
}

이 부분에서 config.setAllowCredentials(true); 부분과 .addAllowedOrigin("*");을 함꼐 사용하지 못한다는 오류이다. 그래서 오류 코드를 자세히 읽어보면 consider using "allowedOriginPatterns" instead. 와 같이 allowedOriginPatterns를 대신 사용하라는 것이다. 그래서 .addAllowedOrigin("*") 부분을 .addAllowedOriginPattern("*") 으로 대체하여 오류를 해결하였다.

수정한 코드

@Bean
CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration config = new CorsConfiguration();
    config.addAllowedOriginPattern("*");
    config.addAllowedHeader("*");
    config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"));
    config.addExposedHeader("Authorization");
    config.addExposedHeader("Authorization-refresh");
    config.addExposedHeader("Set-Cookie");
    config.setAllowCredentials(true);

    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", config);
    return source;
}