1
votes

I am using dropwizard and angular as my UI . My server and my UI are running on different ports. My dropwizard application doesn't seem to set the Origin headers in the response.

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.

Please can you advice what could be the issue

I have setup CORS on dropwizard as follows

 @Override
public void run(MyAppConfiguration myAppConfiguration, Environment environment) throws Exception {
    //Force browsers to reload all js and html files for every request as angular gets screwed up
    environment.servlets()
            .addFilter("CacheBustingFilter", new CacheBustingFilter())
            .addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/*");

    enableCorsHeaders(environment);

}


private void enableCorsHeaders(Environment env) {
        final FilterRegistration.Dynamic cors = env.servlets().addFilter("CORS", CrossOriginFilter.class);

        // Configure CORS parameters
               corsFilter.setInitParameter("Access-Control-Allow-Credentials", "true");
    corsFilter.setInitParameter("Access-Control-Allow-Origin", "*");
    corsFilter.setInitParameter("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Headers, Access-Control-Request-Method, Cache-Control, Pragma, Expires");
    corsFilter.setInitParameter("Access-Control-Allow-Methods\" ", "OPTIONS,GET,PUT,POST,DELETE,HEAD");


        // Add URL mapping
        cors.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*");
    }

Angular Service calling into the REST endpoint

 private reconUrl = "http://localhost:8199/api/iceberg/reconciliations";

  getReconciliations(): Promise<Reconciliation[]> {
    return this.http.get(this.reconUrl)
      .toPromise()
      .then(response => response.json().data as Reconciliation[])
      .catch(this.handleError);
  }

Request-Response Headers

http://localhost:8199/api/iceberg/reconciliations

GET http://localhost:8199/api/iceberg/reconciliations
Accept: application/json, text/plain, */*
Origin: http://localhost:4200
X-DevTools-Emulate-Network-Conditions-Client-Id: 90d7ac77-f45f-4d60-a667-a56da9e0582b
X-DevTools-Request-Id: 7836.4077
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36
Referer: http://localhost:4200/dashboard
Accept-Encoding: gzip, deflate, br
Accept-Language: en-GB,en-US;q=0.8,en;q=0.6

HTTP/1.1 401 Unauthorized
Date: Thu, 06 Jul 2017 10:59:14 GMT
WWW-Authenticate: BASIC realm="application"
Content-Length: 0

PreFlight OPTIONS request/response

My browser is not doing any pre-flight requests so I dont see any OPTIONS request-response.

But I tried CURL with OPTIONS command as below and still see the same issue of 410 Unauthorized request

$ curl -H "Origin: http://example.com"        
-H "Access-Control-Request-Method: POST"        
-H "Access-Control-Request-Headers: X-Requested-With"        
-X OPTIONS --verbose http://localhost:8199/api/iceberg/reconciliations

Curl Command Request-Response below

 * STATE: INIT => CONNECT handle 0x6000578f0; line 1410 (connection #-5000)
    * Added connection 0. The cache now contains 1 members
    * STATE: CONNECT => WAITRESOLVE handle 0x6000578f0; line 1446 (connection #0)
    *   Trying ::1...
    * TCP_NODELAY set
    * STATE: WAITRESOLVE => WAITCONNECT handle 0x6000578f0; line 1527 (connection #0)
    * Connected to localhost (::1) port 8199 (#0)
    * STATE: WAITCONNECT => SENDPROTOCONNECT handle 0x6000578f0; line 1579 (connection #0)
    * Marked for [keep alive]: HTTP default
    * STATE: SENDPROTOCONNECT => DO handle 0x6000578f0; line 1597 (connection #0)
    > OPTIONS /api/iceberg/reconciliations HTTP/1.1
    > Host: localhost:8199
    > User-Agent: curl/7.54.1
    > Accept: */*
    > Origin: http://example.com
    > Access-Control-Request-Method: POST
    > Access-Control-Request-Headers: X-Requested-With
    >
    * STATE: DO => DO_DONE handle 0x6000578f0; line 1676 (connection #0)
    * STATE: DO_DONE => WAITPERFORM handle 0x6000578f0; line 1801 (connection #0)
    * STATE: WAITPERFORM => PERFORM handle 0x6000578f0; line 1811 (connection #0)
    * HTTP 1.1 or later with persistent connection, pipelining supported
    < HTTP/1.1 401 Unauthorized
    < Date: Thu, 06 Jul 2017 10:53:52 GMT
    < WWW-Authenticate: BASIC realm="application"
    < Content-Length: 0
3
Is everything ok with OPTION request? it returns 204 or 200? - Grigoryants Artem
The response headers shown in the question seem to be for a request to http://localhost:4200/dashboard but your code’s making a request to http://localhost:8199/api/myapp/products, not http://localhost:4200. The http://localhost:8199 server is the one that must be set up to send the Access-Control-Allow-Origin response header. But the error message in the question indicates the http://localhost:8199 server is not sending that response header. It doesn’t matter what headers you have the http://localhost:4200 server set up to send. The http://localhost:8199 server is what matters - sideshowbarker
Hi, I have udpated the correct HTTP request-reponse when made from the browser. I also tried CURL with OPTIONS method and got the same issue. My dropwizard application doesnt seem to set the Origin headers in the response. Please can you advice what could be the issue? - serah

3 Answers

0
votes

hey bro if you are using angular cli there is a way first you have to create a file in the project root. More info

https://github.com/angular/angular-cli/blob/cff95a732eaec9c94f41a1476ba9f2524867d11f/docs/documentation/stories/proxy.md

with this content in your case

[
 {
  "context": "/",
  "target": "http://localhost:8199",
  "secure": false,
  "changeOrigin": true
 }
]

after doing this you won't need to select a port in your http call. All your request will go under 8199 port.

I forgot to run you need to add an option like this.

ng serve --proxy-config proxy-local.conf.json

Hope it helps you bro.

0
votes

I faced similar issue with drop-wizard CORS configuration where in every REST API called from web application I was getting issue "Response to preflight request is not 200" .

Eventually I found the problem was the custom filter that I had written for handling in Authentication, so the preflight request were getting intercepted by custom filter & were returning 500 Error .

I handled it by adding CHAIN_PREFLIGHT_PARAM to tthe existing cors parameters as below

cors.setInitParameter(CrossOriginFilter.CHAIN_PREFLIGHT_PARAM, Boolean.FALSE.toString());
0
votes

Please try this one

cors.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, "*");
cors.setInitParameter(CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER,
    "X-Requested-With,Content-Type,Accept,Origin,Authorization");