Monday, November 10, 2014

Enabling CORS With Cookies on Jersey

This previous post shows how to enable basic CORS functionality in Jersey. However, to enable cookies and authentication, more needs to be done. First of all the "Access-Control-Allow-Credentials" header needs to be set, then the other issue is that a wildcard "*" cannot be used with "Access-Control-Allow-Origin". You will either have to specify in hard-code the origins that you will support, or you'll have to use the Origin in the request for this response header.

Sample code:

public class SimpleCorsResponseFilter implements ContainerResponseFilter {
   @Override
   public ContainerResponse filter(ContainerRequest req, ContainerResponse resp) {
       String requestOrigin = req.getHeaderValue("Origin");
       if (requestOrigin == null) {
           return resp;
       }
       else{
             MultivaluedMap<String, Object> headers = resp.getHttpHeaders();
             headers.add("Access-Control-Allow-Origin", requestOrigin);
             headers.add("Access-Control-Allow-Credentials", "true");
             headers.add("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
             headers.add("Access-Control-Allow-Headers", "Content-Type");
             return resp;
       }
   }
}

References (for the wildcard issue):

No comments:

Post a Comment