How to Enable CORS in a Spring Boot Application?

Cross-Origin Resource Sharing (CORS) is a security feature implemented by web browsers. It restricts web pages from making requests to a domain other than the one that served the web page. In some scenarios, for example, when creating RESTful web services or APIs that are consumed by web clients running on another domain, you might need to relax or configure the default security constraints. 

Spring Boot provides first-class support for CORS. In this blog post, we will discuss how you can enable and configure CORS in a Spring Boot application

1. Global CORS Configuration

Add the following bean to one of your configuration classes (for example, main application class annotated with @SpringBootApplication):

import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurer() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**") // all endpoints in the application
                .allowedOrigins("http://localhost:3000", "http://localhost:4200") // allowed origins, can be `*` for all
.allowedMethods("GET", "POST", "PUT", "DELETE") // allowed HTTP methods .maxAge(3600) // caching of pre-flight response .allowedHeaders("Authorization", "Content-Type", "Accept") // allowed headers .exposedHeaders("custom-header1", "custom-header2") .allowCredentials(true); // allow credentials, should be true if using sessions or basic authentication } }; }

2. CORS Configuration on Controller or Request Mapping Level

@CrossOrigin is an annotation in Spring Framework that is used to enable Cross-Origin Resource Sharing (CORS) on specific handler methods or at the controller level. CORS is a security feature implemented by web browsers that restricts web pages from making requests to a domain other than the one that served the web page.

Instead of a global configuration, you can configure CORS for specific controllers or request mappings using @CrossOrigin annotation.

Enable CORS at the Method level:

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {

    @CrossOrigin(origins = "http://example.com")
    @GetMapping("/endpoint")
    public String getEndpoint() {
        return "Hello from endpoint!";
    }
}

In this case, only the /endpoint URL will have CORS headers that allow requests from http://example.com

You can use @CrossOrigin annotation to enable CORS for all the endpoints within a controller:

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@CrossOrigin(origins = "http://example.com")
@RestController
public class MyController {
    @GetMapping("/endpoint")
    public String getEndpoint() {
        return "Hello from endpoint!";
    }
}

3. Advanced CORS Configuration

For more advanced CORS configurations, you can use CorsConfigurationSource:

import org.springframework.context.annotation.Bean;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

@Bean
public CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(Arrays.asList("http://example.com"));
    configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
    configuration.setAllowedHeaders(Arrays.asList("Authorization", "Content-Type"));
    configuration.setExposedHeaders(Arrays.asList("custom-header1", "custom-header2"));
    configuration.setAllowCredentials(true);

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

Note: Be cautious when configuring CORS, especially when allowing all origins (*) or when enabling credentials support. Always make sure your settings are as strict as possible while allowing your specific use case to avoid potential security issues.


Comments