Explain Cross-Origin Resource Sharing (CORS) and how you would configure it in a Spring Boot application.

CORS is a browser-enforced mechanism that lets a server explicitly declare which other origins are allowed to make requests to it, relaxing the default same-origin restriction in a controlled way.

Key Points: • Without CORS configuration, browsers block cross-origin JavaScript calls to your API by default. • @CrossOrigin can be applied at the controller or method level for quick, localized rules. • A global CorsConfigurationSource bean is preferred for consistent, application-wide policy. • You can restrict allowed origins, HTTP methods, headers, and whether credentials (cookies) are permitted. • CORS is not a security boundary against server-to-server calls—it only governs browser-initiated cross-origin requests.

Example: A React app running on localhost:3000 calling a Spring Boot API on localhost:8080 needs the API to allow that origin explicitly, otherwise the browser blocks the response even though the server itself would have processed it fine.

Code Example:

@Bean
public CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowedOrigins(List.of("https://app.example.com"));
    config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE"));
    config.setAllowedHeaders(List.of("Authorization", "Content-Type"));

    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", config);
    return source;
}

Interview Tip: A concise interview answer is:

"CORS lets a server tell browsers which other origins are allowed to call it, since browsers block cross-origin requests by default. In Spring Boot I'd define a global CorsConfigurationSource bean specifying allowed origins, methods, and headers rather than scattering @CrossOrigin annotations across controllers."