Resolving CORS Issues in Spring Boot: Three Configuration Approaches
This article explains the Same Origin Policy, introduces CORS as its solution, and provides three practical Spring Boot configurations—including a global WebMvcConfigurer, a servlet filter, and the @CrossOrigin annotation—to enable cross‑origin requests safely and efficiently.
When a browser enforces the Same Origin Policy (SOP), scripts can only access resources from the same protocol, host, and port, which prevents potentially malicious cross‑site interactions. Cross‑Origin Resource Sharing (CORS) is the W3C standard that allows browsers to make cross‑origin HTTP requests when both client and server support it.
CORS requests are classified as simple or non‑simple. Simple requests (GET, HEAD, POST with limited headers) only need an Origin header, while non‑simple requests trigger a pre‑flight OPTIONS request to verify allowed methods and headers.
To enable CORS in a Spring Boot application, three common approaches are presented:
1. Global configuration using WebMvcConfigurer
import org.springframework.context.annotation.Configuration;<br/>import org.springframework.web.servlet.config.annotation.CorsRegistry;<br/>import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;<br/><br/>@Configuration<br/>public class CorsConfig implements WebMvcConfigurer {<br/> @Override<br/> public void addCorsMappings(CorsRegistry registry) {<br/> registry.addMapping("/**")<br/> .allowedOrigins("*")<br/> .allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")<br/> .allowCredentials(true)<br/> .maxAge(3600)<br/> .allowedHeaders("*");<br/> }<br/>}This method configures CORS globally and works with recent Spring versions; the older WebMvcConfigurerAdapter is deprecated since Spring 5.
2. Servlet filter
import org.springframework.context.annotation.Configuration;<br/>import javax.servlet.*;<br/>import javax.servlet.annotation.WebFilter;<br/>import javax.servlet.http.HttpServletResponse;<br/>import java.io.IOException;<br/><br/>@WebFilter(filterName = "CorsFilter ")<br/>@Configuration<br/>public class CorsFilter implements Filter {<br/> @Override<br/> public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {<br/> HttpServletResponse response = (HttpServletResponse) res;<br/> response.setHeader("Access-Control-Allow-Origin", "*");<br/> response.setHeader("Access-Control-Allow-Credentials", "true");<br/> response.setHeader("Access-Control-Allow-Methods", "POST, GET, PATCH, DELETE, PUT");<br/> response.setHeader("Access-Control-Max-Age", "3600");<br/> response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");<br/> chain.doFilter(req, res);<br/> }<br/>}This filter directly adds the required CORS headers to every response; only one of the first two methods is needed in practice.
3. Annotation‑level configuration with @CrossOrigin
public class GoodsController {<br/> @CrossOrigin(origins = "http://localhost:4000")<br/> @GetMapping("goods-url")<br/> public Response queryGoodsWithGoodsUrl(@RequestParam String goodsUrl) throws Exception {}<br/>}The @CrossOrigin annotation can be placed on a controller class or individual handler methods, providing the most fine‑grained CORS control.
All three approaches achieve the same goal; the effective one follows the nearest‑scope principle, similar to CSS specificity.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
