Raj Bhatia Raj Bhatia - 1 year ago 72
reST (reStructuredText) Question

How to allow multiple domains for CORS with ContainerResponseFilter in Jersy.?

I'm implementing RESTful web service with JAX-RS jersey implementation.
I want to allow multiple domains to access my webservice but not all.
currently I have written below code to allow only one domain for CORS.
Can anyone explain me how to allow specific multiple domains in Jersey implementation.?

public class CORSResponseFilter implements ContainerResponseFilter {

public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {

MultivaluedMap<String, Object> headers = responseContext.getHeaders();
headers.add("Access-Control-Allow-Origin", "www.xxxxx.com");
headers.add("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
headers.add("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, X-Codingpedia");

Answer Source

Set the header value programmatically. Have a predefined list of origins you want to allow. In the filter method, grab the Origin header from the request context. This will have the origin domain of the request. Check that against the list of allowed origins. If it's in the list, then put the domain from the Origin header as the allowed origin. If it's not in there, throw a ForbiddenException saying the origin is not allowed.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download