Spring Boot : CORS Issue

Checkout this guide from Spring:


There are few ways to add CORS support in Spring Boot.

Using global configuration:

public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurerAdapter() {
        public void addCorsMappings(CorsRegistry registry) {

And using @CrossOrigin annotation:

@CrossOrigin(origins = "http://localhost:9000")
public Greeting greeting(@RequestParam(required=false, defaultValue="World") String name) {
    System.out.println("==== in greeting ====");
    return new Greeting(counter.incrementAndGet(), String.format(template, name));

Although Spring security provides a way to configure CORS in http configurer, there's a much cleaner approach to add CORS filter to the application-

public class MyCORSFilter implements Filter {

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;

    response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
    response.setHeader("Access-Control-Allow-Credentials", "true");
    response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With, remember-me");

    chain.doFilter(req, res);

public void init(FilterConfig filterConfig) {

public void destroy() {


Ordering the filter with highest precedence makes sure that MyCORSFilter implementation of javax.servlet.Filter is the first one in the chain. Hope this helps