문제 인식

백엔드 서버는 클라이언트에게 쿠키를 받아 인증 확인을 하는 로직이 있었습니다.

프론트 서버에서 테스트 용으로 인증이 필요한 API 요청을 하니 Cors 에러가 발생했습니다.

 

문제 파악

당시에 스프링부트 Cors 설정을 WebMvcConfigurer 를 이용하여 구현했습니다.

@Configuration
public class CorsConfig implements WebMvcConfigurer {

	@Override
	public void addCorsMappings(final CorsRegistry registry) {
		registry.addMapping("/**")
			.allowedOriginPatterns("http://localhost:3000")
			.allowedMethods("GET", "POST", "PUT", "DELETE", "PATCH")
			.allowedHeaders("*")
			.allowCredentials(true);
	}
}

 

구글 서칭을 해보니 스프링 시큐리티에서 CorsConfigurationSource로 Cors 설정하는 부분이 있음을 확인했습니다.

WebMvcConfigurerCorsConfigurationSource의 차이점은  CorsConfigurationSource가 WebMvcConfigurer 보다 먼저 거치는 필터이였습니다.

 

그렇기 때문에, 쿠키를 사용할 때는 WebMvcConfigurer로 설정한다 한들, CorsConfigurationSource 필터에서 이미 걸려졌기 때문에 Cors 에러가 난 것이였습니다.

 

문제 해결

그래서 필자는 WebMvcConfigurer 대신 스프링 시큐리티 설정 클래스 안에  CorsConfigurationSource 를 구현하고 적용함으로써 해결했습니다.

@Bean
public CorsConfigurationSource corsConfigurationSource() {
    return request -> {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowedHeaders(Collections.singletonList("*"));
        corsConfiguration.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "PATCH"));
        corsConfiguration.setAllowedOriginPatterns(List.of("http://localhost:3000"));
        corsConfiguration.setAllowCredentials(true);
        return corsConfiguration;
    };
}

 

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

    http
        .cors(cors -> cors.configurationSource(corsConfigurationSource()));
        
    // 나머지 설정

+ Recent posts