Let's Build an API Together - Part 30 - CORS

Last Update: 13.02.2018. By Jens in API Series | APIs | Newsletter

When our API is used by anything running in a browser and it this thing running in the browser was not loaded from the same domain our API is running, we will encounter a concept called CORS.

CORS stands for Cross-Origin Resource Sharing and is a concept in the browser to prevent third-party sites and apps from using a particular backend. Basically, the backend can declare in various headers who can access it and what is supported. On the other side of this deal is the browser, who will respect that and prevent any remote calls from Javascript to that backend, i.e., if we disallow all POST request made to use, the browser will not do POST in JS and throw an error.

We can enable this in Spring in a breeze with by defining it in a WebMvcConfigurer. The adapter class of pre Spring Boot 2 versions is not needed anymore, thanks to Java 8 default methods, we can now use the interface directly.

public class WebMVCConfig implements WebMvcConfigurer {

    public void addCorsMappings(CorsRegistry registry) {
            .allowedMethods("GET", "POST", "PUT", "DELETE").allowedHeaders("*")

Here I allow basically anyone to access our API on all endpoints, allow credentials being sent with the request like Authorization headers, allow certain HTTP methods only and also declare that we expose the x-auth-token containing the session token of Spring Session.

When using Spring Security, we also must allow CORS in its config like in the WebSecurityConfigurerAdapter :

protected void configure(HttpSecurity http) throws Exception {
    // rest ....

.cors() is the relevant part here. This allows the OPTIONS request, which is part of the CORS deal and known as preflight, to go through Spring Security.

Want content like this in your inbox each workday irregularly? No BS, spam or tricks... just useful content:

I understand and agree to the privacy policy