[Spring] Cors 에러를 해결하자.

Walter Mitty·2023년 5월 31일
0

칼퇴가 눈치보여서 딱 5분만 더 앉아있다가 가자 하고 2분정도 지났을 때
슬랙으로 메시지가 왔다.

프론트 분 : cors 에러 처리가 안되어 있는 것 같아요.

ㅠ..했는데 안먹힌 것 뿐입니다?

1트 실패후, 2트로 설정한건 Security Config 에서 CorsConfigurationSource 를 Bean으로 등록해 주는 거였다.

원래 배포 전에 쓰던 Cors 설정부분, Local 환경에서만 사용 했었다.

@Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.addAllowedOrigin("http://{ip주소}:5500");
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "OPTIONS", "PUT", "DELETE", "PATCH"));
        configuration.setAllowedHeaders(Arrays.asList("*"));
        configuration.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

배포 후 설정 부분

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.addAllowedOriginPattern("*");
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "OPTIONS", "PUT", "DELETE", "PATCH"));
        configuration.setAllowedHeaders(Arrays.asList("*"));
        configuration.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

잘 보면 configuration.addAllowedOriginconfiguration.addAllowedOriginPattern로 바뀐 것을 볼 수 있는데, 이건 (*)을 사용하기 위해서다.
CorsConfigurationSource에서는 configuration.setAllowCredentials(true); 가 있으면 configuration.addAllowedOrigin("*") 사용이 불가능하기 때문이다.
따라서 뒤에 Pattern 을 붙여주고 달아주면 된다.

0개의 댓글