Quick Tip Cors & Spring Boot

You probably know that we do a lot of native Android and Ionic work but you may not know that we also specialize in backend development using Java and other open-source technologies. Our enterprise Java stack of choice is Spring Boot and this is a quick guide for getting started with CORS (cross domain access) on Spring Boot.

Spring Boot is an offshoot of the popular Spring framework and brings many conveniences from modern non-Java web development frameworks to Spring developers. It’s related to the Spring MVC framework but is more geared toward use in a mirco-services architecture For those that don’t know, CORs is a browser feature that protects against cross-site scripting in JavaScript and the web would be a much more dangerous place without it. As always, security comes at a price and in this case that price is that web services that interact with an API on another domain or IP need to allow cross site access in their response headers or just about every modern browser won’t let the response through.

Ideally, you’d want to change your ‘Access-Allow-Origin header’ to the domains that your client applications will be hitting your API from but if you’re API is public or you don’t yet know what the final domain of your client app, you could simply set the header to '*'.

In Spring Boot this can be done using a filter:

@Component 
public class SimpleCORSFilter implements ContainerResponseFilter {  
    @Override 
    public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
        MultivaluedMap <String, Object> headers = responseContext.getHeaders();
        headers.add("Access-Control-Allow-Origin", "*");
        headers.add("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
        headers.add("Access-Control-Allow-Headers", "*");
    }
}

They key here is the @Component above your subclass of ContainerResponseFilter, that’s what tells the the framework about this calls. What this class does is add the values to the “Access-Control-Allow-Origin, “Access-Control-Allow-Methods”, and the “Access-Control-Allow-Headers”. In the example above, we are going with the most open settings possible. You likely will want more secure / conservative settings unless your service is intended to public. This is an important point and it took me hours to figure it out –It is important that this file be in the same package as your “Application” class (the class that has the SpringApplication.run) in it.

We hope you find this useful and if you have a project you'd like us to help get off the ground or get across the finish line, then contact us