Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Interview question

How do you configure CORS in Spring Boot? स्प्रिंग बूट में CORS को कैसे कॉन्फिगर करें?

Answer

CORS (Cross-Origin Resource Sharing) is a browser security mechanism that blocks a web page from calling an API on a different origin unless the server explicitly allows it via response headers. In Spring Boot, CORS is configured either globally with a WebMvcConfigurer bean or per-controller with @CrossOrigin, specifying allowed origins, methods, and headers.

When Spring Security is also on the classpath, CORS must additionally be enabled inside the security filter chain with http.cors(Customizer.withDefaults()), referencing a CorsConfigurationSource bean — configuring CORS at the MVC layer alone is not enough once Security's filters are in front of the request.

@Bean
public CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowedOrigins(List.of("https://example.com"));
    config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE"));
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", config);
    return source;
}

CORS (Cross-Origin Resource Sharing) एक ब्राउज़र सुरक्षा तंत्र है जो एक वेब पेज को दूसरे ओरिजिन पर API कॉल करने से रोकता है जब तक सर्वर स्पष्ट रूप से रिस्पॉन्स हेडर्स के ज़रिए अनुमति न दे। स्प्रिंग बूट में, CORS को WebMvcConfigurer बीन से ग्लोबली या @CrossOrigin से प्रति-कंट्रोलर कॉन्फिगर किया जाता है।

जब स्प्रिंग सिक्योरिटी भी क्लासपाथ पर हो, तो CORS को सिक्योरिटी फ़िल्टर चेन के अंदर भी सक्षम करना ज़रूरी होता है, CorsConfigurationSource बीन का संदर्भ देते हुए — अकेले MVC लेयर पर CORS कॉन्फिगर करना पर्याप्त नहीं होता।

@Bean
public CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowedOrigins(List.of("https://example.com"));
    config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE"));
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", config);
    return source;
}

Was this answer clear?