문제의 해결
- 백엔드 서버를 Spring Security 전략을 사용하였기 때문에, Spring Security에서 CORS 에러를 잡을 수 있었습니다.
@Bean
public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
httpSecurity.csrf().disable()
.addFilterBefore(corsFilter, UsernamePasswordAuthenticationFilter.class)
.exceptionHandling()
.authenticationEntryPoint(jwtAuthenticationEntryPoint)
.accessDeniedHandler(jwtAccessDeniedHandler)
.and()
.headers()
.frameOptions()
.sameOrigin()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/swagger-ui/**", "/v3/api-docs/**", "/swagger-resources/**").permitAll()
.requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
.antMatchers("/auth/**").authenticated()
.antMatchers("/api/**").permitAll()
.anyRequest().permitAll()
.and()
.cors().configurationSource(corsConfigurationSource())
.and()
.apply(new JwtSecurityConfig(jwtTokenProvider));
return httpSecurity.build();
}
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addExposedHeader("accessToken"); // 노출할 헤더 설정
config.addExposedHeader("refreshToken"); // 노출할 헤더 설정
config.addAllowedOriginPattern("*"); // 모든 ip의 응답을 허용
config.addAllowedHeader("*"); // 모든 header의 응답을 허용
config.addAllowedMethod("*"); // 모든 post, put 등의 메서드에 응답을 허용
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
return source;
}
- 중요한 점은 CorsConfigurationSource를 작성하고 Cors로 등록해주는 점 정도 입니다.