Mastering CORS in Spring Boot: Practical Solutions and Code Samples

This guide explains what CORS is, why browsers enforce same‑origin policies, and provides both frontend and backend strategies—including JSONP, proxy servers, Chrome flags, and several Spring Boot configurations such as filters, @CrossOrigin, custom CorsFilter, and WebMvcConfigurer—to resolve cross‑origin issues.

Big Data and Microservices
Big Data and Microservices
Big Data and Microservices
Mastering CORS in Spring Boot: Practical Solutions and Code Samples

1. Introduction

During development, interface calls between different applications often encounter cross‑origin problems that prevent normal data retrieval. This article defines CORS, explains why it occurs, and presents concrete solutions using a Spring Boot project.

1.1 What is CORS

CORS (Cross‑Origin Resource Sharing) refers to the ability of browsers to request resources from a different domain. The browser’s same‑origin policy restricts JavaScript from accessing content on another site unless the server explicitly allows it.

For example, if site A wants to use Ajax to fetch data from site B and the two sites are on different domains, a cross‑origin issue arises.

Same‑origin conditions Same protocol (http or https) Same IP address (e.g., 192.168.1.2) Same port (e.g., 8080) If any of these differ, a cross‑origin problem occurs.

1.2 CORS Solutions

Frontend solutions

Use JSONP to achieve cross‑origin calls.

Deploy a Node.js proxy server; the frontend sends requests to Node.js, which forwards them to the backend.

Disable browser security for development only (e.g., Chrome --disable-web-security).

Backend solutions

Set the response header Access-Control-Allow-Origin (e.g., via a servlet filter).

Annotate classes or methods with @CrossOrigin in Spring.

Extend Spring Web’s CorsFilter (suitable for Spring MVC and Spring Boot).

Implement the WebMvcConfigurer interface (suitable for Spring Boot).

Other CORS solutions exist; this article focuses on the most commonly used approaches in real projects.

2. Spring Boot CORS Configuration

1. Using a Filter

@WebFilter
public class CorsFilter implements Filter {
    // Logger
    private static Logger logger = LoggerFactory.getLogger(CorsFilter.class);

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
        chain.doFilter(req, res);
    }

    public void init(FilterConfig filterConfig) { /* init logic */ }
    public void destroy() { /* cleanup logic */ }
}

2. Using @CrossOrigin Annotation

@RequestMapping(value = "/v1/users")
@RestController
@CrossOrigin
public class UserController extends BaseController {
    @Autowired
    private UserService userService;

    @RequestMapping(method = RequestMethod.POST)
    @CrossOrigin
    public User create(@Validated User user) {
        return userService.save(user);
    }
}

3. Extending Spring Web’s CorsFilter

package com.garyond.hurricane.config;

import org.springframework.stereotype.Component;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import java.util.Arrays;

/**
 * Cross‑origin configuration
 * @author Garyond
 */
@Component
public class CustomCorsFilter extends CorsFilter {
    public CustomCorsFilter() {
        super(configurationSource());
    }

    private static UrlBasedCorsConfigurationSource configurationSource() {
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.setMaxAge(36000L);
        config.setAllowedMethods(Arrays.asList("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/v1/**", config);
        return source;
    }
}

4. Implementing WebMvcConfigurer

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 CorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowCredentials(true)
                .allowedMethods("GET", "POST", "DELETE", "PUT", "PATCH")
                .maxAge(3600);
    }
}
The above implementations summarize practical CORS configurations used in real Spring Boot projects; feedback is welcome.
backendJavaSpring BootWeb developmentCORS
Big Data and Microservices
Written by

Big Data and Microservices

Focused on big data architecture, AI applications, and cloud‑native microservice practices, we dissect the business logic and implementation paths behind cutting‑edge technologies. No obscure theory—only battle‑tested methodologies: from data platform construction to AI engineering deployment, and from distributed system design to enterprise digital transformation.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.