Adding CORS support to Spring Boot Microservices

Following on from previous posts on creating Spring Boot based Microservices, at some point you’re going to have to consider CORS.

What is CORS?

CORS, or Cross Origin Resource Sharing, is a security check which happens when your browser requests a resource from a different domain to the one you are currently on via a script. So for example, if you have an application on domain1.com and are requesting microservice content from domain2.com, a CORS check will be made.

Essentially what happens is that the remote resource on domain2.com will have to tell the requestor that it accepts requests from domain1.com in order for the request to succeed. This is over and above any other security checks (such as OAuth2) which will be made. Domain2 does this by adding certain HTTP Headers to responses for content.

The header in question is Access-Control-Allow-Origin, if domain2 wanted to allow Domain1 to access it’s content, it could set the domain explicitly in the Header:

Access-Control-Allow-Origin: https://domain1.com

Requests set a header called Origin, which is the domain from which the request originates. The two headers are then used to perform a security check on whether the request should proceed. The header also allows wildcards to be used to allow less restrictive access.

There’s a good article on the Mozilla Developer Network which explains this in detail: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS.

Spring configuration

In the example below I’m adding modifications to an OAuthResourceServerConfiguration class which extends ResourceServerConfigurerAdapter. In that class, I define a new @Bean which returns a CorsFilter. The method itself sets up a configuration which allows requests from http://domain1.com, allows user credentials, allows all headers, and allows GET and PUT methods. Finally it is mapped to all sub URLs.

@Bean
public CorsFilter corsFilter() {

    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true); 
    config.addAllowedOrigin("http://domain1.com");
    config.addAllowedHeader("*");
    config.addAllowedMethod("GET");
    config.addAllowedMethod("PUT");
    source.registerCorsConfiguration("/**", config);
    return new CorsFilter(source);
}

With that in place, the code will allow requests from domain1.com and thereby CORS checks will pass from that domain. If you need to add other methods, or restrict headers or url mapping you can do so via changes to the above method configuration.