Configure OpenID Connect with token exchange using Keycloak

Deployment Platform
Minimum Version
Kong Gateway - 3.14
TL;DR

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

This is a Konnect tutorial and requires a Konnect personal access token.

  1. Create a new personal access token by opening the Konnect PAT page and selecting Generate Token.

  2. Export your token to an environment variable:

     export KONNECT_TOKEN='YOUR_KONNECT_PAT'
    
  3. 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-output
    

    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'
    

    Copy and paste these into your terminal to configure your session.

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.

  1. Export your license to an environment variable:

     export KONG_LICENSE_DATA='LICENSE-CONTENTS-GO-HERE'
    
  2. Run the quickstart script:

    curl -Ls https://get.konghq.com/quickstart | bash -s -- -e KONG_LICENSE_DATA 
    

    Once Kong Gateway is ready, you will see the following message:

     Kong Gateway Ready
    

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.

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:

  1. 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 -
    

To learn more about entities, you can read our entities documentation.

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

  1. 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-exchange
    

    The parameter KC_HOSTNAME=http://localhost:8080 ensures Keycloak always uses localhost:8080 as its token issuer regardless of which URL it’s accessed through. This is required because Kong Gateway performs token exchange via keycloak:8080, and Keycloak must recognize the subject token’s iss claim (localhost:8080) as its own issuer.

  2. Export your issuer URL, Keycloak host, and endpoint URLs to environment variables. For example, using Docker and the default master realm:

    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'
    

    Because we’re using Docker for this demo, we have to configure a few networking parameters:

    • DECK_ISSUER and KEYCLOAK_HOST use localhost because that’s how you access Keycloak from your machine.
    • DECK_JWKS_ENDPOINT and DECK_TOKEN_ENDPOINT use the container name keycloak because Kong Gateway runs inside Docker and reaches Keycloak over the shared kong-quickstart-net network.

    In your own setup, especially running outside of a container, you may not need DECK_JWKS_ENDPOINT and DECK_TOKEN_ENDPOINT.

  3. 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:

  1. In the sidebar, open Clients, then click Create client.
  2. Configure the client:

Section

Settings

General settings
  • Client type: OpenID Connect
  • Client ID: client-1
Capability config
  • Toggle Client authentication to on
  • Make sure that Direct access grants is checked.
Login settings Valid redirect URIs: http://localhost:8000/*

Find the credentials for the first client:

  1. In the sidebar, open Clients, and select client-1.
  2. Open the Credentials tab.
  3. Set Client Authenticator to Client ID and Secret.
  4. Copy the Client Secret.
  5. Export the client ID and secret to environment variables:

    export DECK_CLIENT_ID_1='client-1'
    export DECK_CLIENT_SECRET_1='YOUR-CLIENT-SECRET'
    

Create and configure second client

Create the second client:

  1. In the sidebar, open Clients, then click Create client.
  2. Configure the client:

Section

Settings

General settings
  • Client type: OpenID Connect
  • Client ID: client-2
Capability config
  • Toggle Client authentication to on
  • Make sure that Standard flow and Standard Token Exchange are checked.
Login settings Valid redirect URIs: http://localhost:8000/*

Find the credentials for the second client:

  1. In the sidebar, open Clients, and select client-2.
  2. Open the Credentials tab.
  3. Set Client Authenticator to Client ID and Secret.
  4. Copy the Client Secret.
  5. Export the client ID and secret to environment variables:

    export DECK_CLIENT_ID_2='client-2'
    export DECK_CLIENT_SECRET_2='YOUR-CLIENT-SECRET'
    

Configure client scopes

  1. In the sidebar, open Client scopes, then click Create client scope.
  2. Give the scope a unique name: add-client-2-as-audience.
  3. Save the scope.
  4. Click the Mappers tab.
  5. Click Configure a new mapper and select Audience.
  6. Configure the mapper:

Field

Settings

Name aud-client-2
Included client audience client-2

Apply scope to client

  1. In the sidebar, open Clients and click client-1.
  2. Click Client scopes.
  3. Click Add client scope.
  4. In the modal, check add-client-2-as-audience.
  5. Click Add and set the scope as “Optional”.

Set up user

  1. Switch to the Users menu and add a user.

    In this guide, we’re going to use an example user named alex.

  2. Open the user’s Credentials tab and add a password.

    In this guide, we’re going to use the example password doe.

  3. Disable Temporary Password.
  4. 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, and client secret: Settings that connect the plugin to your IdP (in this case, the sample Keycloak app).
  • using_pseudo_issuer: Disables OIDC discovery from the issuer URL. This is required here because Kong Gateway runs inside Docker and can’t reach localhost:8080 directly. The issuer value is still used to validate the iss claim in incoming tokens.
  • jwks_endpoint and token_endpoint: Explicit endpoint URLs that Kong Gateway uses to fetch signing keys and perform the token exchange. These use the keycloak container 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. The issuer field restricts exchange to tokens from the same IdP, and conditions.has_audience further limits it to tokens that carry client-2 in their aud claim, 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 to profile (Keycloak also includes email by 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 "$KONNECT_PROXY_URL/anything" \
     --no-progress-meter --fail-with-body  \
     -H "Authorization: Bearer $TOKEN"
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

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.

curl -Ls https://get.konghq.com/quickstart | bash -s -- -d

Help us make these docs great!

Kong Developer docs are open source. If you find these useful and want to make them better, contribute today!