10장. CORS는 인증 허용표가 아니다
CORS는 브라우저가 다른 origin의 응답을 JavaScript에 보여 줄지 통제하는 브라우저 정책이다. 서버 간 요청, curl, 악성 앱을 막지 않는다. 인증과 인가를 CORS에 맡기면 안 된다. preflight는 보통 cookie 없이 오므로 Spring Security보다 먼저 처리되어야 한다는 공식 CORS 통합 문서의 순서를 지킨다.
@Bean
CorsConfigurationSource corsConfigurationSource() {
var config = new CorsConfiguration();
config.setAllowedOrigins(List.of("https://app.contracthub.example"));
config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE"));
config.setAllowedHeaders(List.of("Content-Type", "X-CSRF-TOKEN"));
config.setAllowCredentials(true);
var source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/api/**", config);
return source;
}
credential을 허용하면서 origin *를 쓰지 않는다. scheme, host, port가 origin임을 기억한다. preview 도메인을 wildcard로 열기보다 수명과 소유자를 가진 allowlist로 관리한다. 허용되지 않은 origin, 허용된 origin의 preflight, 실제 인증 실패를 각각 테스트해 CORS 오류와 401을 구분한다.