Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keycloak and Spring Boot web app in dockerized environment

Consider the following environment:

  • one docker container is keycloak
  • another docker container is our web app that uses keycloak for authentication

The web app is a Spring Boot application with "keycloak-spring-boot-starter" applied. In application.properties:

keycloak.auth-server-url = http://localhost:8028/auth

A user accessing our web app will be redirected to keycloak using the URL for the exposed port of the keycloak docker container. Login is done without problems in keycloak and the user (browser) is redirected to our web app again. Now, the authorization code needs to be exchanged for an access token. Hence, our web app (keycloak client) tries to connect to the same host and port configured in keycloak.auth-server-url. But this is a problem because the web app resides in a docker container and not on the host machine, so it should rather access http://keycloak:8080 or something where keycloak is the linked keycloak docker container.

So the question is: How can I configure the keycloak client to apply different URLs for browser redirection and access token endpoints?

like image 572
Steffen Harbich Avatar asked Jul 26 '19 05:07

Steffen Harbich


1 Answers

There used to be another property auth-server-url-for-backend-requests but was removed by pull request #2506 as a solution to issue #2623 on Keycloak's JIRA. In the description of this issue, you'll find the reasons why and possible workarounds: that should be solved at the DNS level or by adding entries to the host file.

So there is not much you can do in the client configuration, unless you change the code and make your own version of the adapter, but there is something you can do at the Docker level. For this to work properly, first I suggest you use a fully qualified domain name instead of localhost for the public hostname, as you would in production anyway, eg. keycloak.mydomain.com. You can use a fake one (not registered in DNS servers) if you just add it to the host's /etc/hosts file (or Windows equivalent) as an alias next to localhost.

Then, if you are using Docker Compose, you can set aliases (alternative hostnames) for the keycloak service on the docker network to which the containers are connected (see doc: Compose File reference / Service configuration reference / networks / aliases). For example:

version: "3.7"

services:
  keycloak:
    image: jboss/keycloak
    networks:
      # Replace 'mynet' with whatever user-defined network you are using or want to use
      mynet:
        aliases:
          - keycloak.mydomain.com

  webapp:
    image: "nginx:alpine"
    networks:
      - mynet

networks:
  mynet:

If you are just using plain Docker, you can do the equivalent with --alias flag of docker network connect command (see doc: Container networking / IP address and hostname).

like image 142
cdan Avatar answered Nov 02 '22 05:11

cdan