Nginx에서 CORS 설정을 할 수도 있지만, Spring에서 하는 방법을 알아본다!
return !(ObjectUtils.nullSafeEquals(scheme, originUrl.getScheme()) &&
ObjectUtils.nullSafeEquals(host, originUrl.getHost()) &&
getPort(scheme, port) == getPort(originUrl.getScheme(), originUrl.getPort()));
@Configuration
public class CorsMvcConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedHeaders("*").allowedOrigins("http://localhost:5173").allowedMethods("*");
}
}
public SecurityFilterChain filterChain(HttpSecurity http, JwtUtil jwtUtil) throws Exception {
http.cors(
(cors) ->
cors.configurationSource(
request -> {
CorsConfiguration config = new CorsConfiguration();
config.setAllowedHeaders(Collections.singletonList("*"));
config.setAllowedOrigins(
List.of("http://localhost:5173"));
config.setAllowedMethods(Collections.singletonList("*"));
return config;
}));
...
}
public interface HandlerInterceptor {
default boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
return true;
}
default void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
}
default void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
}
}
WebMvcConfigurationSupport
에서 등록된 인터셉터와 cors 설정을 추가하기 때문이다.public class WebMvcConfigurationSupport implements ApplicationContextAware, ServletContextAware {
...
private void initHandlerMapping() {
...
mapping.setInterceptors(this.getInterceptors(conversionService, resourceUrlProvider));
mapping.setCorsConfigurations(this.getCorsConfigurations());
}
}
// 1. WebMvcAutoConfiguration (자동 설정)
@AutoConfigureOrder(-2147483638)
@ImportRuntimeHints({WebResourcesRuntimeHints.class})
public class WebMvcAutoConfiguration {
}
public static class EnableWebMvcConfiguration extends DelegatingWebMvcConfiguration {
}
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {
...
public void setConfigurers(List<WebMvcConfigurer> configurers) {
if (!CollectionUtils.isEmpty(configurers)) {
this.configurers.addWebMvcConfigurers(configurers);
}
}
public class WebMvcConfigurationSupport implements ApplicationContextAware, ServletContextAware {
...
private void initHandlerMapping() {
...
mapping.setInterceptors(this.getInterceptors(conversionService, resourceUrlProvider));
mapping.setCorsConfigurations(this.getCorsConfigurations());
}
}