curl -i -X GET "$KONNECT_PROXY_URL/anything" \
--no-progress-meter --fail-with-body \
-H "Authorization: Bearer $TOKEN"
Configure OpenID Connect with token exchange using Keycloak
Configure the OpenID Connect plugin with token_exchange settings, using subject_token_issuers to define which incoming tokens are eligible for exchange. Kong Gateway will perform an OAuth 2.0 token exchange (RFC 8693) with your IdP, replacing the incoming token with a new one issued to a different client before forwarding it upstream.
Prerequisites
Kong Konnect
This is a Konnect tutorial and requires a Konnect personal access token.
-
Create a new personal access token by opening the Konnect PAT page and selecting Generate Token.
-
Export your token to an environment variable:
export KONNECT_TOKEN='YOUR_KONNECT_PAT'Copied! -
Run the quickstart script to automatically provision a Control Plane and Data Plane, and configure your environment:
curl -Ls https://get.konghq.com/quickstart | bash -s -- -k $KONNECT_TOKEN --deck-outputCopied!This sets up a Konnect Control Plane named
quickstart, provisions a local Data Plane, and prints out the following environment variable exports:export DECK_KONNECT_TOKEN=$KONNECT_TOKEN export DECK_KONNECT_CONTROL_PLANE_NAME=quickstart export KONNECT_CONTROL_PLANE_URL=https://us.api.konghq.com export KONNECT_PROXY_URL='http://localhost:8000'Copied!Copy and paste these into your terminal to configure your session.
Kong Gateway running
This tutorial requires Kong Gateway Enterprise. If you don’t have Kong Gateway set up yet, you can use the quickstart script with an enterprise license to get an instance of Kong Gateway running almost instantly.
-
Export your license to an environment variable:
export KONG_LICENSE_DATA='LICENSE-CONTENTS-GO-HERE'Copied! -
Run the quickstart script:
curl -Ls https://get.konghq.com/quickstart | bash -s -- -e KONG_LICENSE_DATACopied!Once Kong Gateway is ready, you will see the following message:
Kong Gateway Ready
decK v1.43+
decK is a CLI tool for managing Kong Gateway declaratively with state files. To complete this tutorial, install decK version 1.43 or later.
This guide uses deck gateway apply, which directly applies entity configuration to your Gateway instance.
We recommend upgrading your decK installation to take advantage of this tool.
You can check your current decK version with deck version.
Required entities
For this tutorial, you’ll need Kong Gateway entities, like Gateway Services and Routes, pre-configured. These entities are essential for Kong Gateway to function but installing them isn’t the focus of this guide. Follow these steps to pre-configure them:
-
Run the following command:
echo ' _format_version: "3.0" services: - name: example-service url: http://httpbin.konghq.com/anything routes: - name: example-route paths: - "/anything" service: name: example-service protocols: - http - https ' | deck gateway apply -Copied!
To learn more about entities, you can read our entities documentation.
Set up Keycloak with token exchange
This tutorial requires an identity provider (IdP). If you don’t have one, you can use Keycloak. The steps will be similar in other standard identity providers.
For this tutorial, you will need two clients. We’ll create both in Keycloak.
Install and run Keycloak
-
Install Keycloak (version 26 or later) on your platform.
For example, you can use the Keycloak Docker image. The following command attaches Keycloak to the same network as Kong Gateway so that the OIDC plugin can reach it:
docker run -p 127.0.0.1:8080:8080 \ --name keycloak \ --network kong-quickstart-net \ -e KC_BOOTSTRAP_ADMIN_USERNAME=admin \ -e KC_BOOTSTRAP_ADMIN_PASSWORD=admin \ -e KC_HOSTNAME=http://localhost:8080 \ quay.io/keycloak/keycloak start-dev --features=token-exchangeCopied!The parameter
KC_HOSTNAME=http://localhost:8080ensures Keycloak always useslocalhost:8080as its token issuer regardless of which URL it’s accessed through. This is required because Kong Gateway performs token exchange viakeycloak:8080, and Keycloak must recognize the subject token’sissclaim (localhost:8080) as its own issuer. -
Export your issuer URL, Keycloak host, and endpoint URLs to environment variables. For example, using Docker and the default
masterrealm:export DECK_ISSUER='http://localhost:8080/realms/master' export DECK_JWKS_ENDPOINT='http://keycloak:8080/realms/master/protocol/openid-connect/certs' export DECK_TOKEN_ENDPOINT='http://keycloak:8080/realms/master/protocol/openid-connect/token' export KEYCLOAK_HOST='localhost'Copied!Because we’re using Docker for this demo, we have to configure a few networking parameters:
-
DECK_ISSUERandKEYCLOAK_HOSTuselocalhostbecause that’s how you access Keycloak from your machine. -
DECK_JWKS_ENDPOINTandDECK_TOKEN_ENDPOINTuse the container namekeycloakbecause Kong Gateway runs inside Docker and reaches Keycloak over the sharedkong-quickstart-netnetwork.
In your own setup, especially running outside of a container, you may not need
DECK_JWKS_ENDPOINTandDECK_TOKEN_ENDPOINT. -
-
Open the admin console.
The default URL of the console is
http://localhost:8080/admin/master/console/.
Create and configure first client
Create the first client:
- In the sidebar, open Clients, then click Create client.
- Configure the client:
|
Section |
Settings |
|---|---|
| General settings |
|
| Capability config |
|
| Login settings |
Valid redirect URIs: http://localhost:8000/*
|
Find the credentials for the first client:
- In the sidebar, open Clients, and select
client-1. - Open the Credentials tab.
- Set Client Authenticator to Client ID and Secret.
- Copy the Client Secret.
-
Export the client ID and secret to environment variables:
export DECK_CLIENT_ID_1='client-1' export DECK_CLIENT_SECRET_1='YOUR-CLIENT-SECRET'Copied!
Create and configure second client
Create the second client:
- In the sidebar, open Clients, then click Create client.
- Configure the client:
|
Section |
Settings |
|---|---|
| General settings |
|
| Capability config |
|
| Login settings |
Valid redirect URIs: http://localhost:8000/*
|
Find the credentials for the second client:
- In the sidebar, open Clients, and select
client-2. - Open the Credentials tab.
- Set Client Authenticator to Client ID and Secret.
- Copy the Client Secret.
-
Export the client ID and secret to environment variables:
export DECK_CLIENT_ID_2='client-2' export DECK_CLIENT_SECRET_2='YOUR-CLIENT-SECRET'Copied!
Configure client scopes
- In the sidebar, open Client scopes, then click Create client scope.
- Give the scope a unique name:
add-client-2-as-audience. - Save the scope.
- Click the Mappers tab.
- Click Configure a new mapper and select Audience.
- Configure the mapper:
|
Field |
Settings |
|---|---|
| Name |
aud-client-2
|
| Included client audience |
client-2
|
Apply scope to client
- In the sidebar, open Clients and click
client-1. - Click Client scopes.
- Click Add client scope.
- In the modal, check
add-client-2-as-audience. - Click Add and set the scope as “Optional”.
Set up user
-
Switch to the Users menu and add a user.
In this guide, we’re going to use an example user named
alex. -
Open the user’s Credentials tab and add a password.
In this guide, we’re going to use the example password
doe. - Disable Temporary Password.
- Save the credential.
Enable the OpenID Connect plugin with token exchange
Using the Keycloak and Kong Gateway configuration from the prerequisites, configure the OpenID Connect plugin on example-route to act as client-2 and narrow the token scopes:
echo '
_format_version: "3.0"
plugins:
- name: openid-connect
route: example-route
config:
issuer: "${{ env "DECK_ISSUER" }}"
using_pseudo_issuer: true
jwks_endpoint: "${{ env "DECK_JWKS_ENDPOINT" }}"
token_endpoint: "${{ env "DECK_TOKEN_ENDPOINT" }}"
client_id:
- client-2
client_secret:
- "${{ env "DECK_CLIENT_SECRET_2" }}"
auth_methods:
- bearer
token_exchange:
subject_token_issuers:
- issuer: "${{ env "DECK_ISSUER" }}"
conditions:
has_audience:
- client-2
request:
scopes:
- profile
' | deck gateway apply -
Auth configuration:
-
issuer,client ID, andclient secret: Settings that connect the plugin to your IdP (in this case, the sample Keycloak app). -
using_pseudo_issuer: Disables OIDC discovery from theissuerURL. This is required here because Kong Gateway runs inside Docker and can’t reachlocalhost:8080directly. Theissuervalue is still used to validate theissclaim in incoming tokens. -
jwks_endpointandtoken_endpoint: Explicit endpoint URLs that Kong Gateway uses to fetch signing keys and perform the token exchange. These use thekeycloakcontainer name, which is reachable from Kong Gateway over the shared Docker network. -
auth_methods: Specifies that the plugin should use bearer auth.
In this example, we are also using the following token_exchange settings:
-
subject_token_issuers: Defines which incoming tokens are eligible for exchange. Theissuerfield restricts exchange to tokens from the same IdP, andconditions.has_audiencefurther limits it to tokens that carryclient-2in theiraudclaim, which is the audience we explicitly added via the scope mapper in the Keycloak setup. -
request.scopes: The scopes that the exchanged token should be restricted to. In this case, the exchanged token’s scope is narrowed toprofile(Keycloak also includesemailby default).
This configuration tells Kong Gateway to trigger a token exchange whenever an incoming bearer token was issued by the same IdP and has client-2 in its aud claim, which is the audience we explicitly added via the scope mapper.
The exchange requests a new token issued to client-2 with a narrowed scope.
Validate the flow
Obtain a token from Keycloak as a client-1 user, including the add-client-2-as-audience optional scope so that client-2 is added to the audience:
TOKEN=$(curl -s -X POST \
http://$KEYCLOAK_HOST:8080/realms/master/protocol/openid-connect/token \
-d "grant_type=password" \
-d "client_id=client-1" \
-d "client_secret=$DECK_CLIENT_SECRET_1" \
-d "username=alex" \
-d "password=doe" \
-d "scope=openid profile add-client-2-as-audience" | jq -r .access_token) && echo $TOKEN
If you decode the token, the resulting access token will have an aud claim containing client-2, and an azp claim with client-1:
{
"azp": "client-1",
"aud": ["client-2", "account"],
"scope": "openid profile email",
"iss": "http://localhost:8080/realms/master",
"exp": 1775253107,
"iat": 1775253047
}
Send the token to Kong Gateway:
curl -i -X GET "http://localhost:8000/anything" \
--no-progress-meter --fail-with-body \
-H "Authorization: Bearer $TOKEN"
The response shows the Authorization header that Kong Gateway forwarded to the upstream service. When decoded, the token should look something like this:
{
"azp": "client-2",
"aud": "account",
"scope": "profile email",
"iss": "http://localhost:8080/realms/master",
"exp": 1775253114,
"iat": 1775253054
}
The token should be a different one, with azp set to client-2, no client-1 in aud, and scope narrowed to profile email, confirming the token exchange and scope narrowing took effect.
Cleanup
Clean up Konnect environment
If you created a new control plane and want to conserve your free trial credits or avoid unnecessary charges, delete the new control plane used in this tutorial.
Destroy the Kong Gateway container
curl -Ls https://get.konghq.com/quickstart | bash -s -- -d