I need to implement CORS support in Jersey based REST server. I've gone through some of the available material and informative tutorials . I found two approaches people are using:
Approach-1 :
Simple and direct approach where implement one HTTP
filter which adds CORS
header to response (Jersey specific)
public class ResponseCorsFilter implements ContainerResponseFilter {
public ContainerResponse filter(ContainerRequest req, ContainerResponse contResp) {
ResponseBuilder resp = Response.fromResponse(contResp.getResponse());
resp.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
String reqHead = req.getHeaderValue("Access-Control-Request-Headers");
if(null != reqHead && !reqHead.equals(null)){
resp.header("Access-Control-Allow-Headers", reqHead);
}
contResp.setResponse(resp.build());
return contResp;
}
}
Approach-2 :
Fully implement CORS as per its specification i.e. preflight request handling and all header support. Inspected source code of one such open-source java implementation cors-filter
My question is which approach should be taken when? What could be the downside of approach-1 vs approach-2?
My use case is all origins/methods can be allowed and Authorization
HTTP header would be part of all REST
requests. I am inclined towards approach-1 as it seems most of the default CORS settings would suffice my use case but not sure if not having full CORS specs implemented at server side would create any issues whatsoever.