Spring Boot CORS Cross Origin with Integration Test

Spring Boot CORS Cross Origin with Integration Test

Add CORS to a request mapping

@CrossOrigin(value = "https://my-allowed-domain.com")
@RequestMapping(value = "/". method = RequestMethod.GET)
public ResponseEntity<Void> testFunction(){
    return new ResponseEntity<>(HttpStatus.OK);
}

Add CORS to a request mapping using application properties value

Change @CrossOrigin to reference the value from the application properties.

Let’s assume the CORS header domain is stored in an application.properties stored as config.headers.cors=https://my-allowed-domain.com

@CrossOrigin(value = "${config.headers.cors}")
@RequestMapping(value = "/". method = RequestMethod.GET)
public ResponseEntity testFunction(){
    return new ResponseEntity<>(HttpStatus.OK);
}

Integration test for CORS domains

This tests that requests made with the correct origin domains are granted access to the resource:

    @Test
    public void correctOriginHeaderTest() throws Exception {

        MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/")
                .contentType(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON)
                .header("Access-Control-Request-Method", "GET")
                .header("Origin", "https://my-allowed-domain.com");

        mockMvc.perform(builder)
                .andExpect(MockMvcResultMatchers.status().isOk());
    }

This tests that requests made from disallowed domains are denied access to the resource:

    @Test
    public void wrongOriginHeaderTest() throws Exception {

        MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/")
                .contentType(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON)
                .header("Access-Control-Request-Method", "GET")
                .header("Origin", "http://disallowed-domain.com");

        mockMvc.perform(builder)
                .andExpect(MockMvcResultMatchers.status().isForbidden());

    }

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.