Accessing Service by its Docker Network Alias

  docker, jwt, keycloak, networking, open-liberty

Scenario

I have secured webservice (JakartaEE + Microprofile + JWT) running in open liberty. As issuer of the jwt token I use keycloak. For testing and development i want to run both services in docker. Therefore I wrote a docker-compose file. As test client I use JUnit with microprofile-client. This is running outside of docker.

Problem

I can retrieve the JWT-Token via localhost at the host – e.g.:

POST /auth/realms/DC/protocol/openid-connect/token HTTP/1.1
Host: localhost:8080
Content-Type: application/x-www-form-urlencoded

realm=DC&grant_type=password&client_id=dc&username=dc_editor&password=******

The problem is, that from the perspective of the webservice localhost isn’t the keycloak server.

Goal

I want to access the keycloak server from the host with its docker-internal network alias – e.g. dcAuthServer

By the way I have to work in user land, hence I cannot change hosts-files. This was one suggestion along my long search for a solution.

Code

The docker-compose file looks like this:

version: "3.8"
services:
  dcWebservice:
    environment:
      - DC_AUTH_SERVER_HOST=dcAuthServer
      - DC_AUTH_SERVER_PORT=8080
      - DC_AUTH_SERVER_REALM=DC
    image: dc_webservice:latest
    ports:
    - "9080:9080"
    networks:
      - dcNetwork

  dcAuthServer:
    image: dc_keycloak:latest
    ports:
    - "8080:8080"
    networks:
      dcNetwork:
        aliases:
            - dcAuthServer
    healthcheck:
      test: "curl --fail http://localhost:8080/auth/realms/DC || false"

networks:
  dcNetwork:

The environment DC_AUTH* are used in the mpJwt-configuration in server.xml of the open liberty server:

<mpJwt id="dcMPJWT" audiences="dc" issuer="http://${DC_AUTH_SERVER_HOST}:${DC_AUTH_SERVER_PORT}/auth/realms/${DC_AUTH_SERVER_REALM}"
           jwksUri="http://${DC_AUTH_SERVER_HOST}:${DC_AUTH_SERVER_PORT}/auth/realms/${DC_AUTH_SERVER_REALM}/protocol/openid-connect/certs"/>

The issuer is where I have to put a trusted issuer for the JWT-Token.

I hope I did not forget important information – just ask!

Thanks in advance
Robert

Source: StackOverflow

LEAVE A COMMENT