Troubleshooting
Spring CORS 세팅 - addAllowedOriginPattern, isPreFlightRequest 관련 문제
DuL2
2022. 8. 17. 09:41
TroubleShooting
발생한 문제
프론트엔드와 백엔드의 협업 과정에서 API 서버를 열기 위해 CORS 필터를 설정해주었으나 몇 가지 잘못된 설정으로 제대로된 통신이 되지 않는 듯 하였다.
해결 및 시도 방법
1. 검색해보니 스프링 부트의 버정에 따른 설정 방법의 차이가 생긴듯 하였다.
- 스프링 부트 2.4.0 버전 이상부터 "allowCredentials 가 true일 때 allowedOrigins의 값이 "*"이면 안된다"는 에러 문구처럼 설정할 수 없었고 대신 allowOriginPatterns를 사용해야 한다고 한다.
세부사항 변화
Origin 을 OriginPattern 메소드 사용으로 변경
@Configuration
public class CorsConfig {
// CORS 정책에서 벗어나기 위한 구성
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowCredentials(true); // 내 서버가 응답할 때 json을 자바스크립트에서 처리할 수 있게 할지를 설정하는 것. false로 하면 자바스크립트로 요청했을때 오지 않음.
configuration.addAllowedOriginPattern("*"); //모든 ip로부터 접속 허용.
configuration.addAllowedHeader("*"); //모든 header 접속 허용.
configuration.addAllowedMethod("*"); //모든 HTTP Method, get, post, put 등등 접속 허용.
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
Security Filter Chain 에서 reqeust가 CORS 의 preflight인지 확인하여 인가 과정을 Permit하도록 설정해주었다.
.authorizeRequests()
.requestMatchers(request -> CorsUtils.isPreFlightRequest(request)).permitAll()
회고
. 처음 협업이고 CORS를 설정을 제대로 해본 것 같아 공부가 되었고, 실제로 프론트에서 CORS preflight가 OPTIONS 메소드로 와야하지만 POST로 오는 프론트의 코드도 고치게 되면서 실제적으로는 복합적인 문제로 인한 에러를 해결하게 되었다.
프론트 분들도 실제 API 서버를 통해 협업을 하는 것이 처음이라 같이 공부하고 조율해야 할 부분이 많다는 것을 깨달았다.