0

I need cross origin REST call support for my APIs. Currently I have something like this.

@OPTIONS
public Response options() {
     return Response.ok()
           .header("Access-Control-Allow-Origin", "*")
           .header("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept")
           .header("Access-Control-Allow-Methods", "GET")
                .build();
 }

@GET
@Path("/algorithms")
@Produces("application/json")
public Response getAllAlgorithms() {
    List<MLAlgorithm> mlAlgorithms = MLCoreServiceValueHolder.getInstance().getAlgorithms();
    return Response.ok(mlAlgorithms).build();
}

I used a Rest client[1] for firefox to test API calls. When I do an OPTIONS call to the "/api/configs" API , and check the Response headers, I see only the following.

Status Code: 200 OK
Allow: GET
Content-Length: 0
Date: Mon, 23 Nov 2015 12:17:39 GMT
Server: WSO2 Carbon Server

The first two headers are not set in the response header. I need cross origin support for all APIs in the class. How do I implement this, and what is the issue in the current implementation.

[1] https://addons.mozilla.org/en-US/firefox/addon/restclient/

DesirePRG
  • 6,122
  • 15
  • 69
  • 114
  • If that is what you see then none of the three headers are set. This looks like an interpreted version of the headers to me, as in the "access-control-allow-methods" header is transformed into the output "allow: get". Did you try to do the actual API call? – Gimby Nov 23 '15 at 14:04
  • I used CURL also. same Output – DesirePRG Nov 23 '15 at 14:09
  • You used CURL to do what :/ Minimal responses don't help. – Gimby Nov 23 '15 at 14:15
  • This was my curl call for the API "curl -X options "Content-Type: application/json" -H "Authorization: Basic YWRtaW46YWRtaW4=" -v https://localhost:9443/api/configs -k" and i got the same response headers – DesirePRG Nov 23 '15 at 14:16

1 Answers1

0

Instead of trying to add CORS support in a resource method you should use a filter instead. The problem with the resource method tactic, is that you will need to have the same method for every endpoint location. If a request is made to /api/config, then that endpoint must also have an OPTIONS method to handle the preflight. Same with all other endpoints. So best to just put it in a filter that can handle all requests.

You can see an example (for JAX-RS 2.0 and Jersey 1.x) in this answer

Community
  • 1
  • 1
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720