Source Code Tracing — Enable CORS in Spring Boot

Jeffrey Chen
2 min readJan 30, 2021

--

Cross-origin resource sharing (CORS) is a mechanism that allows a web page to request some resources in different domains. If you are developing some resource service that may be accessed by the front-end app located in a different domain, then you should enable the CORS.

Recap the Spring Boot request flow as above. Spring Boot provides 2 ways to enable the CORS in your service. One is filter based implementation and another is controller based implementation.

Filter Based Implementation

Generally, you can implement org.springframework.web.filter.CorsFilter and register this filter in proper order. For example,

However, if you adopt Spring Security in your project, you can follow the below example to set up your Spring Security configuration which will automatically add the org.springframework.web.filter.CorsFilter into the springSecurityFilterChain. By the way, I have written a story about how to set up Spring Security properly here.

Controller Based Implementation

In the WebMvcConfigurer, there also provides a method for developers to enable the CORS. You can follow the below example to set up the configuration.

After you add the above setting, when the client sends the preflight request to the service, Spring MVC Dispatcher will pass the request to the PreFlightHandler which will handle the request based on your setting.

The last thing you should be aware of is checking the CORS related setting of the Proxy Server or Load Balancer which may handle the CORS request by themselves rather than route the request to your service. That’s the real root cause that makes our front-end APP always got CORS error. 😂

--

--

Jeffrey Chen
Jeffrey Chen

Written by Jeffrey Chen

Software engineer who’s dream is to become an athletes

No responses yet