Enabling CORS in Spring

There are multiple ways to enable CORS in Spring Boot.

Enable CORS Globally

To apply CORS settings to all endpoints in your Spring application, you can use the WebMvcConfigurer interface.

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

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**") // Apply to all endpoints
                .allowedOriginPatterns("*") // Allow all origins
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") // Allow specific methods, We can * for all methods
                .allowedHeaders("*") // Allow all headers
                
    }
}

Enable CORS for Specific Endpoints

You can use the @CrossOrigin annotation to enable CORS for specific controllers or methods. This approach is ideal if you want fine-grained control over which endpoints support CORS.

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

@RestController
@CrossOrigin(origins = "https://google.com", maxAge = 3600) // Allow requests from specific origin
public class MyController {

    @GetMapping("/hello")
    public String example() {
        return "Hello World";
    }
}

Using @CrossOrigin on a Specific Method

@GetMapping("/hello")
@CrossOrigin(origins = "https://google.com", allowedHeaders = {"Authorization", "Content-Type"})
public String example() {
    return "Hello World";
}

3. Enable CORS in Spring Security

If your application uses Spring Security, you must configure CORS in the security settings, as security filters are applied before the controller methods are invoked.

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.cors.CorsConfigurationSource;

@Configuration
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.cors() // Enable CORS
            .and()
            .csrf().disable() // Disable CSRF for simplicity
            .authorizeRequests()
            .anyRequest().authenticated();
        return http.build();
    }

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.addAllowedOrigin("https://example.com"); // Allow specific origin
        configuration.addAllowedMethod("*"); // Allow all HTTP methods
        configuration.addAllowedHeader("*"); // Allow all headers
        configuration.setAllowCredentials(true); // Allow credentials

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

Related Post