harsh
harsh

Reputation: 7692

CORS Java server side implementation

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.

Upvotes: 8

Views: 5088

Answers (2)

Igor Costa
Igor Costa

Reputation: 184

For those who have problem in Play Framework here's a solution, most text is in Portuguese but you can use Google translator.

Solutions is same.

http://www.igorcosta.com/habilitando-cors-no-play-framework-2-3-x/

Upvotes: 0

monsur
monsur

Reputation: 47897

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?

Upvotes: 2

Related Questions