JAX RS injected URIInfo returning localhost for REST requests in reverse proxy

Viewed 1552

I have a set of IBM Websphere Liberty profiles servers inside a HAProxy reverse proxy. Everything works ok but HAProxy is doing something on requests so I can't get the correct URL in the requests using uriInfo.getBaseUri() or uriInfo.getRequestUriBuilder().build("whatever path")... they both return localhost:9080 as host and port, so I can't build correct URLs pointing to the service. (The request is a standard http://api.MYHOST.com/v1/... REST request )

Of course, I get a uriInfo object using @Context in the method so it gets the request information.

Front end configuration:

  reqadd X-Forwarded-Proto:\ http
  # Add CORS headers when Origin header is present
  capture request header origin len 128
  http-response add-header Access-Control-Allow-Origin %[capture.req.hdr(0)] if { capture.req.hdr(0) -m found }
  rspadd Access-Control-Allow-Methods:\ GET,\ HEAD,\ OPTIONS,\ POST,\ PUT  if { capture.req.hdr(0) -m found }
  rspadd Access-Control-Allow-Credentials:\ true  if { capture.req.hdr(0) -m found }
  rspadd Access-Control-Allow-Headers:\ Origin,\ X-Requested-With,\ Content-Type,\ Accept  if { capture.req.hdr(0) -m found }

And Back-end configuration is:

  option forwardfor
  http-request set-header Host api.MYHOST.com
  http-request set-header X-Forwarded-Host %[dst]
  http-request set-header X-Forwarded-Port %[dst_port]

Any ideas on how to get the real request?

2 Answers

I just faced this very issue on my Jersey based application, I used uriInfo.getBaseUriBuilder() to get a UrlBuilder and figured out that it's possible to change the hostname from localhost by using the .host() method

.host(InetAddress.getLocalHost().getHostName())

And you can remove the port part by setting it to -1

.port(-1)

So from a URL that looks like

https://127.0.0.1:8443/hello

I got

https://yourhostname/hello
Related