Resolving CORS Issues in Spring Boot: Concepts, Headers, and Three Implementation Approaches
This article explains the Same Origin Policy, introduces CORS as its solution, details the required response headers, and provides three practical ways—global configuration, servlet filter, and @CrossOrigin annotation—to enable cross‑origin requests in Spring Boot applications.
In modern front‑end/back‑end separated architectures, cross‑origin requests are a common problem; the article starts by describing the Same Origin Policy (SOP) and why browsers enforce it to protect users from malicious scripts.
CORS (Cross‑Origin Resource Sharing) is a W3C standard that allows browsers to make XMLHttpRequest or Fetch calls to a different origin when both the client and server support it, effectively solving the SOP limitation.
The article lists the essential CORS response headers:
Access-Control-Allow-Origin (required)
Access-Control-Allow-Methods (required)
Access-Control-Expose-Headers (optional)
Access-Control-Allow-Credentials (optional)
Access-Control-Max-Age (optional)
Three implementation methods are presented.
1. Global configuration using 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("*")
.allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
.allowCredentials(true)
.maxAge(3600)
.allowedHeaders("*");
}
}This approach configures CORS globally; older tutorials may use the now‑deprecated WebMvcConfigurerAdapter class, which is no longer needed since Spring 5 and Java 8 provide default methods.
/**
* An implementation of {@link WebMvcConfigurer} with empty methods allowing
* subclasses to override only the methods they're interested in.
*
* @author Rossen Stoyanchev
* @since 3.1
* @deprecated as of 5.0 {@link WebMvcConfigurer} has default methods
* (made possible by a Java 8 baseline) and can be implemented directly without
* the need for this adapter
*/
@Deprecated
public abstract class WebMvcConfigurerAdapter implements WebMvcConfigurer {}2. Servlet filter that manually sets CORS headers
import org.springframework.context.annotation.Configuration;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebFilter(filterName = "CorsFilter ")
@Configuration
public class CorsFilter implements Filter {
@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-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, PATCH, DELETE, PUT");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
chain.doFilter(req, res);
}
}This filter adds the necessary headers to every response; using either the global config or the filter is sufficient.
3. Using the @CrossOrigin annotation on controllers or methods
public class GoodsController {
@CrossOrigin(origins = "http://localhost:4000")
@GetMapping("goods-url")
public Response queryGoodsWithGoodsUrl(@RequestParam String goodsUrl) throws Exception {}
}The @CrossOrigin annotation can be placed on a class or method to enable fine‑grained CORS control.
@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CrossOrigin {}All three methods achieve the same goal; the first two are broader, while the annotation provides the most precise control. The article concludes that developers can choose the approach that best fits their project without waiting for front‑end teams to raise CORS issues.
Top Architect
Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.