Spring boot and CORS

A while back I wrote a post Building a REST service with Spring and today I needed to try out the CORS support to allow a similar Spring based REST service to allow for CORS access from a React application I’m working on.

It’s super easy to allow access to all clients by simply adding @CrossOrigin to your controller, for example

package demo;

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@CrossOrigin
@RestController
public class SampleController {

    @RequestMapping("/purchaseOrder")
    public PurchaseOrderType getPurchaseOrder() {
        return new PurchaseOrderType(1234);
    }
}

Equally we can just add the same annotation to REST methods instead of the whole controller, for example

@CrossOrigin
@RequestMapping("/purchaseOrder")
public PurchaseOrderType getPurchaseOrder() {
   return new PurchaseOrderType(1234);
}

Note: @CrossOrigin is the equivalent of @CrossOrigin(origins = “*”).

If we want to limit the origins then we simply use the following instead

@CrossOrigin(origins = "http://localhost:3000")

// or an array of origins like this

@CrossOrigin(origins = {"http://localhost:3000", "http://localhost:3001"})