Pål Pål -3 years ago 158
Java Question

CORS with basic HTTP Authentication

I'm having some problems using basic HTTP Authentication with CORS: We have a node express web server (UI), calling a HTTP API from a Java Dropwizard (Jersey) server, running on the same host.

The API is protected with HTTP basic authentication, and I''ve implemented the following filter on my Jersey server (taken from this post: How to handle CORS using JAX-RS with Jersey):

public class CORSFilter implements ContainerResponseFilter {

public void filter(ContainerRequestContext request,
ContainerResponseContext response) throws IOException {
response.getHeaders().add("Access-Control-Allow-Origin", "http://localhost:9000");
"Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With");
response.getHeaders().add("Access-Control-Allow-Credentials", "true");
response.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");

However, when I try to load the web UI, my console gives me the following output:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:9000/intraday/parameters. (Reason: CORS header ‘Access-Control-Allow-Origin’ does not match ‘http://localhost:9000’)

I'm unable to make sense of this error. Clearly the origin is the same (http://localhost:9000), so I don't get why it doesn't match.

I've also made sure that any preflighted OPTIONS requests are answered with HTTP code 200.

Answer Source

From the description in the question, it sounds like the Java Dropwizard (Jersey) server is running on http://localhost:9000 and the node express web server (UI) is running at another origin.

Regardless, you must set the value of the Access-Control-Allow-Origin response header in the CORSFilter code on the Jersey server to the origin of the frontend JavaScript code that’s making the request (apparently the node server). So if that’s, e.g., http://localhost:12345, then:

response.getHeaders().add("Access-Control-Allow-Origin", "http://localhost:12345");

It anyway must be something other than http://localhost:9000, because there’s no way your browser would emit that “disallows reading the remote resource at http://localhost:9000/… error message if the frontend JavaScript code the request is getting sent from is being served from http://localhost:9000—since in that case it wouldn’t be a cross-origin request and your browser wouldn’t be blocking access to the response.

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