0

I have the next REST controller method:

    @GetMapping("/product-group")
    public List<ProductGroup> getAllProductGroups(@RequestHeader MultiValueMap<String, String> headers){
        final String header = headers.getFirst("Access-Control-Request-Method");
        assert header != null;
        return repository.findAll();
    }

And integration test with org.springframework.boot.test.web.client.TestRestTemplate:

    @Test
    void allowAllHosts() {
        final HttpHeaders headers = new HttpHeaders();
        headers.setOrigin("localhost");
        headers.setAccessControlRequestMethod(HttpMethod.GET);

        final ResponseEntity<?> response = restTemplate.exchange("/product-group",
                HttpMethod.GET,
                new HttpEntity<>(headers),
                String.class);

        assertTrue(response.getHeaders().containsKey("Access-Control-Allow-Origin"), "CORS header doesn't presented");
    }

The test above failed with header == null. Also, I checked in the debugger that headers added by me are missed. But presented different:

* "accept" -> "text/plain, application/json, application/*+json, */*"
* "user-agent" -> "Java/11.0.11"
* "host" -> "localhost:37795"
* "connection" -> "keep-alive"

Why TestRestTemplate override my headers or why it got rid of them at all? And how can I add headers properly?

Volodya Lombrozo
  • 2,325
  • 2
  • 16
  • 34
  • How is the MVC set up for the test? – crizzis May 28 '21 at 18:09
  • @crizzis I haven't any additional configuration. I'm using Spring Boot version 2.4.4. And I have annotation ```@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)``` over my test class. – Volodya Lombrozo May 31 '21 at 08:35

1 Answers1

0

The problem comes from "not allowed headers". JDK ignores a predefined array of headers including Access-Control-Request-Method and Origin during a request. You can find a detailed answer here.

In short, you can add the next line of code:

System.setProperty("sun.net.http.allowRestrictedHeaders", "true");

and the TestRestTemplate will include all headers.

Volodya Lombrozo
  • 2,325
  • 2
  • 16
  • 34