Server Side CORS Java Execution

I need to implement CORS support on a Jersey REST server. I looked through some of the available materials and informative tutorials . I found two approaches that people use:

Approach 1:

A simple and direct approach where one HTTP filter is implemented that adds a CORS header to the response (specific Jersey)

 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 in accordance with its specification, that is, processing pre-flight request and supporting all headers. Investigated source code for one such open source Java implementation cors-filter

My question is which approach should be taken when? What could be the disadvantage of approach-1 versus approach-2?

My use case is that all source / methods can be enabled, and the Authorization HTTP header will be part of all REST requests. I am inclined towards approach-1, since, apparently, most of the default CORS settings would be sufficient for my use, but were not sure that if it were not for the complete CORS specifications implemented on the server side, they would not pose any problems.

+6
source share
2 answers

For your goals, approach number 1 sounds good. Approach No. 2 is more suitable for the case when you have different answers based on the type of request or you want to check the information about the request. If your answer is the same in all types of queries, # 1 should be fine. Please note that since your implementation basically allows all requests to succeed, you must do your own checks to make sure the request is valid. Since you allow the authorization header, I assume you know about it and check the authorization token?

+1
source

For those who have problems in the Play Framework, there is a solution here, most of the texts are in Portuguese, but you can use the Google translator.

The solutions are the same.

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

0
source

All Articles