Securing APIs with Kong and Keycloak - Part 1 by Joshua A Erney and Example Thank you very much
- Kong 2.8.3 - alpine
- Keycloak 20.0.1
- only support kong 2.x.x
create dockerfile and use lua rock with kong-oidc
build image for kong-oidc
docker-compose build kong
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.
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
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
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"