CORS in Spring Boot


🔹 What is CORS?

  • By default, a browser blocks frontend apps running at a different origin (e.g., http://localhost:3000) from calling APIs at another origin (e.g., http://localhost:8080).
  • CORS is a mechanism that allows servers to specify which origins are allowed.

🔹 Ways to Enable CORS in Spring Boot

1. Enable CORS on a specific controller

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

@RestController
public class HelloController {

    // Allow only requests from http://localhost:3000
    @CrossOrigin(origins = "http://localhost:3000")
    @GetMapping("/hello")
    public String hello() {
        return "Hello from Spring Boot!";
    }
}

➡️ Now, if your React/Angular/Vue frontend (running on port 3000) calls /hello, it will succeed.


2. Enable CORS globally with WebMvcConfigurer

If you want all endpoints to allow specific origins:

import org.springframework.context.annotation.Bean;
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 {

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")   // apply to all endpoints
                        .allowedOrigins("http://localhost:3000")
                        .allowedMethods("GET", "POST", "PUT", "DELETE")
                        .allowedHeaders("*");
            }
        };
    }
}

3. Enable CORS with Spring Security (if security is enabled)

If you’re using Spring Security, CORS must also be configured there:

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;

@Configuration
public class SecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .cors()  // Enable CORS
            .and()
            .csrf().disable()
            .authorizeHttpRequests(auth -> auth
                .anyRequest().permitAll()
            );
        return http.build();
    }
}

And also provide a CorsConfigurationSource bean:

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

import java.util.List;

@Configuration
public class CorsConfig {

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(List.of("http://localhost:3000"));
        configuration.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE"));
        configuration.setAllowedHeaders(List.of("*"));
        
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        
        return source;
    }
}

🔹 Example Flow

  • Frontend (React) running at: http://localhost:3000
  • Backend (Spring Boot) running at: http://localhost:8080

React frontend calls:

fetch("http://localhost:8080/hello")
  .then(res => res.text())
  .then(data => console.log(data));

➡️ Without CORS → ❌ Blocked by browser.
➡️ With proper CORS config → ✅ Response: "Hello from Spring Boot!"

Leave a Reply