Want to improve as a dev?

I send a short email every workday about Spring topics, API development and improving as a dev.

I understand and agree to the privacy policy

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

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.

@Configuration
public class WebMVCConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
            .allowedOrigins("*")
            .exposedHeaders("x-auth-token")
            .allowedMethods("GET", "POST", "PUT", "DELETE").allowedHeaders("*")
            .allowCredentials(true).maxAge(3600);
    }
}

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 :

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable()
    .cors().and()
    // 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.


comments powered by Disqus