Search code examples
nginxkeycloakkongredirect-uri

Keycloak redirection issue behind proxy (Kong)


I'm trying to setup a Keycloak instance to handle the users of my webapp. This instance would be, like all others microservices, hidden behind a reverse proxy (Kong, it's a nginx-based proxy).

On my local setup, Kong listens to https://localhost, and keycloak listens to http://localhost:8082/auth. To achieve that, I used several environment variables on my Keycloak container :

ENV KC_HOSTNAME=localhost
ENV KC_HOSTNAME_PORT=8082
ENV KC_HOSTNAME_STRICT_HTTPS=false
ENV KC_PROXY=edge
ENV PROXY_ADDRESS_FORWARDING=true
ENV KC_HTTP_ENABLED=true
ENV KC_HTTP_PORT=8082
KC_HTTP_RELATIVE_PATH=/auth

The setup of Kong configuration looks fine, and the keycloak endpoints that I need are exposed correctly through Kong (/realms, /js, /resources, /robots.txt, like the doc said). Kong handles the TLS connection, and then speaks to all microservices with HTTP only, thus KC_PROXY=edge. /admin is not exposed, I though I could access this locally using localhost:8082 on the right machine.

If I go to https://localhost/auth/realms/master/.well-known/openid-configuration, I get the configuration. However, Keycloak does not know it's behind Kong, so all endpoints contains localhost:8082. That seems normal, since it's how I set it up in the first place.

I tried to add a new realm with a different Frontend URL, calling it https://myapp.com Now, my openid configuration contains https://myapp.com:8082/... everywhere. All the workflows get wrongs URLs. What did I miss ? I cannot remove this port that I put in the first place, otherwise I will not be able to access the admin console. I thought I could do something with KC_HOSTNAME_ADMIN, but unfortunately there is no KC_HOSTNAME_ADMIN_PORT.. or is there ?

Thank you for reading :)


Solution

  • In case it's of interest to someone, the solution was actually quite simple. I should not have set the HOSTNAME and HOSTNAME_PORT in the first place. ENV KC_HOSTNAME_STRICT_HTTPS=false is mandatory, and also I needed to add a plugin to Kong to tweak the headers :

    plugins
    - name: post-function
      service: keycloak
      config:
        functions:
          - return function()
              if ngx.var.upstream_x_forwarded_port == "8000" then
                ngx.var.upstream_x_forwarded_port = 80
              elseif ngx.var.upstream_x_forwarded_port == "8443" then
                ngx.var.upstream_x_forwarded_port = 443
              end
            end
    

    Otherwise, keycloak would have the wrong redirect uri in some cases.