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.
For your purposes, approach #1 sounds sufficient. Approach #2 is more for the case where you have different responses based on the request type, or you want to validate the request information. If your response is the same across all request types, #1 should be fine. Note that because your implementation is basically allowing all requests to succeed, you should be doing your own checks to make sure the request is valid. Since you are allowing the Authorization header, I'm assuming you are aware of this, and are validating the authorization token?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With