Archive for Spring

Programming Pitfalls: Cors & Spring Boot

It’s no secret that I have been dipping my toes back into the world of enterprise Java development over the last moth or so. Thankfully, I haven’t been forced to go full Java EE. In fact for enterprise development I’m getting off pretty easy in the form of 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 mircoservices architecture. I’ll be working in it for a few more weeks and will get some more thoughts together at a later date but for now let’s go over the pain that is CORs. 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.

In Spring Boot this can be done with a simple Filter like so:

@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", "*");
    }
}

Notice the @Component above your subclass of ContainerResponseFilter, that’s what tells the the framework about this calls. What this calss 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 intentded 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.

I hope this helps somebody! If you found this post interesting reach out to me on Twitter.