기존에는 WebMvcConfigurer를 사용해 addCorsMaapins 메서드를 오버라이드함으로써 Cors 문제를 다음과 같이 해결 하였다. (local로 개발중이기 때문에 Origin은 일단 다 허용해 두었다.)
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET", "POST", "PUT", "DELETE");
}
}
이번에는 Spring Security 필터레벨에서 Cors를 적용함으로써 필터 체인 내에서 일관된 CORS 정책을 적용하는 방법을 적용하기로 하였다.
먼저 CorsFilter를 설정하기 위해서 CorsConfigurationSource를 작성해야 한다.
@Value("${host.frontend.imf}")
private String frontendHostUrl;
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.setAllowedOrigins(List.of(frontendHostUrl));
config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE"));
config.setAllowedHeaders(List.of("*"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
return source;
}
orgin은 로컬에서 개발할 때와 배포환경에서 달라지는 것을 고려하여 스프링부트-configuartion과-actuator 에서 공부하였던 @Value
를 사용하여 application.properties파일에 작성된 url을 가져오도록 설정하였다.
참고로 로컬 개발환경의 application.properties에는 이렇게 작성되어 있다.
host.frontend.imf=http://localhost:9002
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception{
...
//http.cors(cors -> cors.disable());
http.cors(cors -> cors.configurationSource(corsConfigurationSource()));
...
return http.build();
}
다음으로는 처음에 disable() 해 주었던 cors필터에 corsConfigurationSource()를 설정해주면 cors문제가 해결되는 것을 확인 할 수 잇다.