Ad

How Can I Add CORS Functionality Into My Http-gateway (spring-integration-dsl)?

I have got a reactjs frontend which sends a request to my api based on spring-integration.

The problem I got is, that I don't know how to bind the CORS functionality in my gateway.

I tried something like this

  @Bean
    public CrossOrigin cors(){
        CrossOrigin c = new CrossOrigin();
        c.setOrigin("/**");
        return c;
    }
@Bean
    public IntegrationFlow httpGetTest() {
        return IntegrationFlows.from(httpGetGateTest()).channel("http.test.channel").handle("testEndpoint", "hello").get();
    }
@Bean
    public MessagingGatewaySupport httpGetGateTest() {
        HttpRequestHandlingMessagingGateway handler = new HttpRequestHandlingMessagingGateway();
        handler.setRequestMapping(createMapping(new HttpMethod[]{HttpMethod.GET}, "/test"));
        handler.setCrossOrigin(cors());
        handler.setHeaderMapper(headerMapper());
        return handler;
    }

Request:

axios.get('http://localhost:8080/test')
    .then(res=>{console.log(res)})

My endpoint returns "Hello World"

Failed to load resource: the server responded with a status of 415 ()
Access to XMLHttpRequest at 'http://localhost:8080/test' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Ad

Answer

First of all, please, be sure that your client really send an Origin HTTP request header. Otherwise the CORS filtering is not applied to the request: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

Although it sounds like it is there anyway: from origin 'http://localhost:3000'.

Consider to change your setOrigin("/**") to the setOrigin("*"). The Cross-Origin policy is about the whole ULR (domain to be precise), not relative path.

BTW, there is a Java DSL factory in Spring Integration for HTTP components:

@Bean
public IntegrationFlow httpGetTest() {
    return IntegrationFlows.from(Http.inboundGateway("/test")
                .requestMapping(r -> r.methods(HttpMethod.GET))
                .crossOrigin(cors -> cors.origin("*"))
                .headerMapper(headerMapper()))
          .channel("http.test.channel")
          .handle("testEndpoint", "hello")
          .get();
}
Ad
source: stackoverflow.com
Ad