2

Is there a way to know the preflight request headers in Java Jersey or is there a way to send different response to a preflight request?

Suppose I have the following code:

@Path("/releaseClient")
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public JSONObject  releaseClient(JSONObject clientAndUser, @Context HttpServletRequest request) throws JSONException{
    int clientId = clientAndUser.getInt("id");
    String userId = clientAndUser.getString("user");
    JSONObject res = new JSONObject();

    // Check if profile is locked by current user and if so release profile
    if(clientLockService.unlockClient(clientId, userId)){
        res.put("success", clientService.returnClientInfo(clientId));
    } else {
    // If not then set error message
        res.put("error", "Profile is not locked by current user");
    }
    return res;
}

Now first the browser will send a preflight request. Is there a way where I can manipulate the response headers for a preflight request?

Pritam Banerjee
  • 17,953
  • 10
  • 93
  • 108

1 Answers1

4

You can't do it in a resource method, unless you want to create a bunch of @OPTIONS methods, as the preflight is an OPTIONS request. Instead you should use a filter. You can see an example implementation here. It's not the greatest implementation, as it doesn't actually check for the preflight, it just sends the CORS headers for all request. If you look at the bottom of the post, it will link to a RESTEasy implementation of a filter to handle CORS. It is a much better implementation. You may want to study that one to get some ideas

Community
  • 1
  • 1
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
  • Yes, I tried @Option methods earlier, but could never capture those in the debugger, nor does it have any logs. May be I did something wrong. But is that the only way? – Pritam Banerjee Apr 26 '16 at 19:41
  • Use a filter. It's your best bet. – Paul Samsotha Apr 26 '16 at 19:42
  • Used the filters as well. But did not solve the CORS issue. Was using Chromium portable. Got that to work only after disabling the web security. But that was not the best practice, so trying to find a better solution. – Pritam Banerjee Apr 26 '16 at 19:43
  • You may need to handle it at the servlet level then. Try to write a servlet filter. [For example](https://github.com/swagger-api/swagger-samples/blob/master/java/java-jersey2/src/main/java/io/swagger/sample/util/ApiOriginFilter.java) – Paul Samsotha Apr 26 '16 at 19:44
  • Ok, might have to try that. There are no methods in Javascript that can handle this. That makes life even more difficult. – Pritam Banerjee Apr 26 '16 at 20:01