/kong-keycloak

Primary LanguageDockerfileMIT LicenseMIT

Kong / Keycloak Only support kong 2.x.x

Credits

Securing APIs with Kong and Keycloak - Part 1 by Joshua A Erney and Example Thank you very much

Installed versions

  • Kong 2.8.3 - alpine
  • Keycloak 20.0.1

Noted

  • only support kong 2.x.x

1. Create the image of Kong + Oidc

create dockerfile and use lua rock with kong-oidc

1.1 Construction of the docker image

build image for kong-oidc

docker-compose build kong

2. Kong DB + Database Migrations

Start kong-db service:

docker-compose up -d kong-db

migrations:

docker-compose run --rm kong kong migrations bootstrap

✋ In case you're upgrading kong from previous versions, probably you may need to run migrations. In this case, you can give this command:

docker-compose run --rm kong kong migrations up

start kong:

docker-compose up -d kong

check service running:

docker-compose ps

check plug in available:

curl -s http://localhost:8001 | jq .plugins.available_on_server.oidc

The result of this call should be true. The presence of the plugin does not indicate that it is already active.

3. Creation of a service and a route

create service for mock api

$ curl -s -X POST http://localhost:8001/services \
    -d name=mock-service \
    -d url=https://{{GUID}}.mockapi.io/api/v1/:{{endpoint}}

copy service id and create route to the service

$ curl -s -X POST http://localhost:8001/services/{{service id}}/routes -d "paths[]=/mock"

Test:

$ curl -s http://localhost:8000/mock

4. Keycloak containers

Create keycloak service:

docker-compose up -d keycloak-db
docker-compose up -d keycloak

Keycloak will be available at the url http://localhost:8180.

config Realm, client secret

5. Kong configuration as Keycloak client

Config oidc plugin

$ curl -s -X POST http://localhost:8001/plugins \
  -d name=oidc \
  -d config.client_id=${CLIENT_ID} \
  -d config.client_secret=${CLIENT_SECRET} \
  -d config.bearer_only=yes \
  -d config.realm=${REALM} \
  -d config.introspection_endpoint=http://${HOST_IP}:8180/realms/${REALM}/protocol/openid-connect/token/introspect \
  -d config.discovery=http://${HOST_IP}:8180/auth/realms/${REALM}/.well-known/openid-configuration \

Get access token

TOKEN=$(curl -s -X POST \
        -H "Content-Type: application/x-www-form-urlencoded" \
        -d "username=demouser" \
        -d "password=demouser" \
        -d 'grant_type=password' \
        -d "client_id=myapp" \
        http://${HOST_IP}:8180/realms/${REALM}/protocol/openid-connect/token \
        |jq . )

echo $TOKEN
export TKN=$(echo $RAWTKN | jq -r '.access_token')
echo $TKN

Test access api with token

curl "http://${HOST_IP}:8000/mock" \
-H "Accept: application/json" \
-H "Authorization: Bearer $TKN"