Configure CORS filter for a web application with Spring Boot
This post will discuss how to configure CORS filter for a web application with Spring Boot.
CORS stands for Cross-Origin Resource Sharing, and it is a mechanism that allows web browsers to request resources from different origins (domains, protocols, or ports) than the one that serves the web page. CORS is useful for enabling cross-domain communication and accessing web services that are hosted on different servers. However, CORS also poses a security risk, as it can expose sensitive data or allow malicious requests to bypass the same-origin policy. Therefore, CORS needs to be configured properly on both the client and the server side.
In Spring Boot, there are several ways to configure CORS filter for a web application, depending on the level of granularity and flexibility we need. Here are some of the possible methods:
1. Using @CrossOrigin Annotation
This is a simple and declarative way to enable CORS for specific controller classes or methods. The @CrossOrigin annotation can be applied at the class level or the method level, and it supports various attributes to customize the CORS configuration, such as origins, methods, allowedHeaders, exposedHeaders, allowCredentials, or maxAge. Here’s an example:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
// Enable CORS for all methods in this controller class @CrossOrigin(origins = "http://domain1.com") @RestController @RequestMapping("/account") public class AccountController { // Enable CORS for this method only @CrossOrigin(origins = "http://domain2.com") @GetMapping("/{id}") public Account retrieve(@PathVariable Long id) { // ... } // Inherit the CORS configuration from the class level @DeleteMapping("/{id}") public void remove(@PathVariable Long id) { // ... } } |
2. Using WebMvcConfigurer Interface
This is a more global and programmatic way to enable CORS for the entire web application. The WebMvcConfigurer interface provides a method called addCorsMappings() that allows us to register CORS configurations for specific URL patterns. We can implement this interface in a configuration class and override this method to customize the CORS filter. Here’s an example:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
@Configuration public class WebConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { // Enable CORS for all endpoints under /api registry.addMapping("/api/**") .allowedOrigins("http://domain1.com") .allowedMethods("GET", "POST", "PUT", "DELETE") .allowedHeaders("Content-Type", "Authorization") .exposedHeaders("X-Custom-Header") .allowCredentials(true) .maxAge(3600); } } |
3. Using CorsFilter Class
This is a more flexible and low-level way to enable CORS for the entire web application. The CorsFilter class is a generic filter that implements the CORS specification and can be registered as a bean in the application context. The CorsFilter class takes a CorsConfigurationSource as a constructor argument, which provides the CORS configuration for each request. We can create a custom CorsConfigurationSource bean that returns a CorsConfiguration instance based on some logic or criteria. Here’s an example:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
@Bean public CorsFilter corsFilter() { // Create a CorsConfigurationSource bean CorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); // Create a CorsConfiguration instance CorsConfiguration config = new CorsConfiguration(); // Configure the allowed origins, methods, headers, etc. config.addAllowedOrigin("http://domain1.com"); config.addAllowedMethod("*"); config.addAllowedHeader("*"); // Apply the configuration to all paths source.registerCorsConfiguration("/**", config); // Create and return a new CorsFilter with the configuration source return new CorsFilter(source); } |
That’s all about configuring CORS filter for a web application with Spring Boot.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)