Video in progress
Why does a CORS error happen, and how do you configure it properly in Spring?
When a page on another domain sends a request, the browser checks the Access-Control-Allow-* headers to see whether the server allows it. If not, it doesn't hand the response to JavaScript. In Spring you configure CORS together with Security, with an explicit list of domains.
📖 Answer
The situation: the frontend is https://app.shop.uz, the API is https://api.shop.uz. Before a non-simple request (say, one with an Authorization header or a JSON POST), the browser sends an OPTIONS preflight. If the server doesn't answer correctly, the console shows:
Access to fetch at 'https://api.shop.uz/orders' from origin 'https://app.shop.uz'
has been blocked by CORS policy
CORS is a browser rule. Postman or curl show no error, which is why the backend says "it works for me" while the frontend says it doesn't work.
Configuration:
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration c = new CorsConfiguration();
c.setAllowedOrigins(List.of("https://app.shop.uz"));
c.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE"));
c.setAllowedHeaders(List.of("Authorization", "Content-Type"));
c.setAllowCredentials(true);
UrlBasedCorsConfigurationSource s = new UrlBasedCorsConfigurationSource();
s.registerCorsConfiguration("/api/**", c);
return s;
}
// in the SecurityFilterChain: http.cors(Customizer.withDefaults())
A common mistake is configuring only @CrossOrigin or a WebMvcConfigurer and forgetting Security: the preflight gets a 401 in Security. And allowedOrigins("*") together with allowCredentials(true) is outright forbidden, and wrong from a security standpoint too.
Sign up to mark studied questions and save your progress.