CORS in Spring Boot controls which frontend origins are allowed to make cross-origin requests to the backend, configured either per-controller with @CrossOrigin or globally through a WebMvcConfigurer bean.
Key Points: • @CrossOrigin(origins = "...") on a controller or method scopes the policy to that specific endpoint. • A global WebMvcConfigurer overriding addCorsMappings applies a consistent CORS policy across all controllers. • allowedOrigins should list explicit trusted domains rather than a wildcard when credentials are involved. • allowedMethods and allowedHeaders can further restrict which HTTP verbs and headers cross-origin requests may use. • CORS is a browser-enforced mechanism, so it protects browser clients but isn't a substitute for server-side authorization.
Example: A single-page app hosted at https://app.example.com calls the Spring Boot API at a different origin; without CORS configuration the browser blocks the response, so the backend explicitly allows that origin through a global CORS configuration.
Code Example:
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("https://app.example.com")
.allowedMethods("GET", "POST", "PUT", "DELETE");
}
}Interview Tip: A concise interview answer is:
"I configure CORS globally with a WebMvcConfigurer overriding addCorsMappings, restricting allowedOrigins to the specific frontend domain rather than using a wildcard, especially if credentials are involved. For a one-off endpoint, @CrossOrigin on the controller works too, but I prefer the global, centralized approach for consistency."