11

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?

2
  • Whatever it is that causes the problem, I don't think it is within the snippets you have posted in the question. I just tried it on a fresh Spring Boot (1.3.2.) setup with a minimum amount of code and the CORS headers are correctly added when I POST from other domains. What version of Boot are you using and from what user agent do you POST your requests? May other dependencies in your project override your Cors settings (or maybe more explicit configuration on the controllers?)?
    – sthzg
    Commented Jan 27, 2016 at 13:16
  • I use Spring Boot 1.3.0.RELEASE and user agent is Firefox. Actually it is Api-gateway application which redirects to other endpoints of other spring boot applications. I use Zuul from netflix. Commented Jan 27, 2016 at 14:16

2 Answers 2

26

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

2
  • If you are using http basic authentication, don't forget to add the token Authorization in Access-Control-Allow-Headers. Commented May 11, 2017 at 19:51
  • 4
    The Filter being implemented here is javax.servlet.Filter
    – Tadhg
    Commented Nov 28, 2017 at 18:58
-1

You not specified all attributes which required for correctly processing. Minimum variant:

path="/**"
allowed-origins="*"
allowed-methods="GET"
allowed-origin-patterns=".*"

Usually path="/**", allowed-origins="*" etc. not safety variant. I understand that making a lot of code class with different configuration - not extendable variant for long pipeline


I can proposition using my implementation for this or you can fork this code
add dependency

<dependency>
  <groupId>io.github.iruzhnikov</groupId>
  <artifactId>spring-webmvc-cors-properties-autoconfigure</artifactId>
  <version>VERSION</version>
</dependency>

and add configuration

spring:
  web:
    cors:
      enabled: true
      mappings:
        baseOrigins:
          paths: /**
          allowed-origins: "http://localhost:4200"
          allowed-origin-patterns: .*

Not the answer you're looking for? Browse other questions tagged or ask your own question.