What is CORS

CORS stands for Cross Origin Request Resource Sharing. CORS is a protocol that defines how a client (the browser) and a server negociate allowing the handling of cross origin requests via HTTP headers.

Why do I see CORS

CORS happens when a page served by a given URL (or origin) tries to load resources from another URL.
In such a situation, the browser traps the embedded call and issues a pre-flight HTTP call to the server in order to see how CORS is allowed by the server.

Handle CORS with Spring Boot

Add a Filter

package com.example.app.utils;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class CorsFilter implements Filter {

	private final Logger log = LoggerFactory.getLogger(CorsFilter.class);

	public CorsFilter() {
		log.info("SimpleCORSFilter init");
	}

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

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

		if (request.getHeader("Origin") != null) {
			response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
		}

		response.setHeader("Access-Control-Allow-Credentials", "true");
		response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
		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);
	}

	@Override
	public void init(FilterConfig filterConfig) {
	}

	@Override
	public void destroy() {
	}
}

MVC Configuration

package com.example.app.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

@Configuration
public class WebMvcConfiguration2 extends WebMvcConfigurationSupport {

	private static final Logger LOGGER = LoggerFactory.getLogger(WebMvcConfiguration2.class);
	
	@Override
	protected void addCorsMappings(CorsRegistry registry) {
		super.addCorsMappings(registry);
		LOGGER.info("WebMVC configuration : addCorsMappings");
		registry.addMapping("/**").allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS");
	}
}

Annotate the controller

package com.example.app.hello;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.CrossOrigin;


@RestController
@RequestMapping("/hello")
@CrossOrigin
public class HelloController {

  @Autowired
  private HelloService helloService;
	
	
  @RequestMapping(value="")
  public Greeting index() {				
    return new Greeting("Hello World !");
  }	
}

Advertisements