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 and are requesting microservice content from, a CORS check will be made.

Essentially what happens is that the remote resource on will have to tell the requestor that it accepts requests from 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:


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:

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, allows user credentials, allows all headers, and allows GET and PUT methods. Finally it is mapped to all sub URLs.

public CorsFilter corsFilter() {

    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = new CorsConfiguration();
    source.registerCorsConfiguration("/**", config);
    return new CorsFilter(source);

With that in place, the code will allow requests from 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.