Cross-Origin Resource Sharing (CORS) is a mechanism that lets resources on a web page be requested from a domain outside the one the page originated from. It relaxes the same-origin policy — the security measure that prevents JavaScript from making requests across domain boundaries.
The simplest fix for a CORS error is allowing the origin directly on the controller with
@CrossOrigin:
@RestControllerpublic class DemoController {
@GetMapping("/demo") @CrossOrigin("http://localhost:8080") public String demo() { return "hello world"; }}This allows requests to /demo from http://localhost:8080 — a page served from that origin can
call this endpoint without being blocked by the browser’s same-origin policy. A request from any
other origin is blocked unless the server includes the right CORS headers. Using the wildcard *
with @CrossOrigin allows all origins.
@CrossOrigin directly on a controller isn’t typically done in production, though — it’s more
common to configure CORS inside the security filter chain, for more control and flexibility:
@Beanpublic SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http.authorizeHttpRequests().anyRequest().permitAll();
http.cors(c -> { CorsConfigurationSource source = request -> { CorsConfiguration config = new CorsConfiguration(); config.setAllowedOrigins( List.of("www.example.com", "www.another.com")); config.setAllowedMethods( List.of("GET", "POST")); config.setAllowedHeaders(List.of("*")); return config; }; c.configurationSource(source); });
return http.build();}Here the CORS policy allows requests from www.example.com and www.another.com, restricted to
GET and POST. setAllowedHeaders specifies which HTTP headers can be used in the actual
request.