Spring Boot and CORS

ghz 1years ago ⋅ 758 views

Question

I facing issue with CORS in spring boot. I have configured CORS like this

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**");
    }
}

which I suppose enables all header and other stuff.

It works excellently with GET request

 $.get("someUrl, function(data, status){
     console.log(data[0].latitude);
 });

But whenever I make POST request like this

 $.ajax({
        url: 'someUrl',
        type: 'post',
        dataType: 'json',
        crossDomain: true,
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            console.log(data);
        },
        data: object
    });

I get the following

OPTIONS XHR  "someUrl" [HTTP/1.1 403 Forbidden 4ms]
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at  "someUrl". 
(Reason: CORS header 'Access-Control-Allow-Origin' missing).

How can I solve this issue?


Answer

Simple way of configuring CORS filter with Spring Boot app is to make @Component class which implements Filter like this:

@Component
public class SimpleCORSFilter 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-Methods", "POST, GET, PUT, OPTIONS, DELETE, PATCH");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        response.setHeader("Access-Control-Expose-Headers", "Location");
        chain.doFilter(req, res);
    }

    @Override
    public void init(FilterConfig filterConfig) {}

    @Override
    public void destroy() {}

}

It works great with spring-boot 1.3.0

EDIT (October 2017):

Still works with spring-boot 1.5.8