Testing CORs in SpringBootTest
The CORS request needs to include an Origin
header for the server to process it. The mock GET request is not having this header. The API does allow us to include headers in the mock requests.
public MockHttpServletRequestBuilder header(String name, Object... values)
Add a header to the request. Values are always added. Parameters: name - the header name values - one or more header values
Here is the code that works
.perform(options("/test-cors")
.header("Access-Control-Request-Method", "GET")
.header("Origin", "http://www.someurl.com"))
Both headers are required, and the configuration
requires that allowed origins and methods align with the values passed in the test.
Instead of initializing the CorsConfigurationSource Bean Simply initialize CorsFilter straight up. Just change that method like this and try,
@Bean
public CorsFilter corsFilter() {
CorsConfiguration configuration = new CorsConfiguration();
List<String> allowedMethods = CORS_ALLOWED_METHODS;
configuration.setAllowedMethods(allowedMethods);
configuration.setAllowedOrigins(CORS_ALLOWED_ORIGINS);
configuration.setAllowedHeaders(CORS_ALLOWED_HEADERS);
configuration.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return new CorsFilter(source);
}
HTH!