Set up OIDC attribution for AI Cost Management

TL;DR

Add your OpenID Connect (OIDC) identity provider as a trusted IdP in Access Management with automatic user provisioning enabled, then create an openid-connect AI Auth Strategy with principals.enabled and principals.jit set, and attach it to the AI Model.

The first authenticated request creates a matching principal automatically, and Konnect records the usage event’s subject as principal/PRINCIPAL_UUID.

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 AI Gateway quickstart script to automatically provision a control plane and data plane in Kong Konnect, and configure your environment:

    curl -Ls https://get.konghq.com/ai | bash -s -- -k $KONNECT_TOKEN \
       -e KONG_CUSTOM_PLUGIN_STREAMING_ENABLED=on

This sets up a AI Gateway control plane named ai-quickstart, provisions a local data plane, and prints out the following environment variables export:

export AI_GATEWAY_ID=your-gateway-id
export KONNECT_TOKEN=$KONNECT_TOKEN
export KONNECT_CONTROL_PLANE_NAME=ai-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.

Want a fully-hosted AI Gateway? See AI Gateway 2.0 on Dedicated Cloud Gateways.

This tutorial uses kongctl to manage Konnect resources programmatically. We recommend keeping kongctl up to date with the latest version (1.28.1).

  1. Install kongctl from developer.konghq.com/kongctl.
  2. Verify the installation:

    kongctl version
  1. Create an OpenAI account.
  2. Get an API key.
  3. Export the API key as a variable:
     export OPENAI_API_KEY="<YOUR_OPENAI_API_KEY>"
     export OPENAI_AUTH_HEADER="Bearer $OPENAI_API_KEY"

This guide uses ngrok to expose a local URL to the internet for local testing and development purposes.

  1. Install ngrok.
  2. Sign up for an ngrok account and find your ngrok authtoken.
  3. Install the authtoken and connect the ngrok agent to your account:
    ngrok config add-authtoken <TOKEN>
  4. Run ngrok:
    ngrok http 8080
  5. Copy the Forwarding URL from the output.
  6. In a new terminal window, export it as an environment variable:
    export NGROK_HOST='YOUR_FORWARDING_URL'

This guide requires an OIDC provider. In this example, we’ll use Keycloak, but the steps are similar in any standard OIDC provider. Because Konnect is cloud-hosted, it needs to reach your Keycloak instance over the public internet, so set up the ngrok tunnel prerequisite first.

Run Keycloak

Run Keycloak with its hostname set to your ngrok tunnel, so the tokens it issues use that URL as the issuer. KC_PROXY_HEADERS tells Keycloak to trust the forwarded headers ngrok sends, so it reports https in the issuer instead of the http it sees internally:

docker run -p 127.0.0.1:8080:8080 \
  --name keycloak \
  -e KC_BOOTSTRAP_ADMIN_USERNAME=admin \
  -e KC_BOOTSTRAP_ADMIN_PASSWORD=admin \
  -e KC_HOSTNAME=$NGROK_HOST \
  -e KC_PROXY_HEADERS=xforwarded \
  quay.io/keycloak/keycloak start-dev

Export your issuer URL, using the default master realm:

export OIDC_ISSUER_URL="$NGROK_HOST/realms/master"

Create a client for the client credentials grant

Get an admin access token from Keycloak’s built-in admin-cli client, using the password grant with the admin credentials you set above:

ADMIN_ACCESS_TOKEN=$(curl -X POST "$NGROK_HOST/realms/master/protocol/openid-connect/token" \
     --no-progress-meter --fail-with-body  \
     -H "Content-Type: application/x-www-form-urlencoded" \
     -d "grant_type=password" \
     -d "client_id=admin-cli" \
     -d "username=admin" \
     -d "password=admin"  | jq -r ".access_token"
)

Create a client with service accounts enabled, using the Keycloak Admin REST API:

curl -X POST "$NGROK_HOST/admin/realms/master/clients" \
     --no-progress-meter --fail-with-body  \
     -H "Authorization: Bearer $ADMIN_ACCESS_TOKEN" \
     --json '{
       "clientId": "ai-cost-management",
       "protocol": "openid-connect",
       "publicClient": false,
       "serviceAccountsEnabled": true,
       "clientAuthenticatorType": "client-secret"
     }'

Export the client ID:

export OIDC_CLIENT_ID='ai-cost-management'

Keycloak’s client create response has no body, so look up the client’s internal ID by its clientId:

KEYCLOAK_CLIENT_UUID=$(curl -X GET "$NGROK_HOST/admin/realms/master/clients?clientId=$OIDC_CLIENT_ID" \
     --no-progress-meter --fail-with-body  \
     -H "Authorization: Bearer $ADMIN_ACCESS_TOKEN" | jq -r ".[0].id"
)

Fetch the generated client secret:

OIDC_CLIENT_SECRET=$(curl -X GET "$NGROK_HOST/admin/realms/master/clients/$KEYCLOAK_CLIENT_UUID/client-secret" \
     --no-progress-meter --fail-with-body  \
     -H "Authorization: Bearer $ADMIN_ACCESS_TOKEN" | jq -r ".value"
)

Set an email on the service account

Enabling service accounts creates a Keycloak user named service-account-<clientId> to represent this client. Look up that user:

KEYCLOAK_SERVICE_ACCOUNT_USER_ID=$(curl -X GET "$NGROK_HOST/admin/realms/master/users?username=service-account-$OIDC_CLIENT_ID" \
     --no-progress-meter --fail-with-body  \
     -H "Authorization: Bearer $ADMIN_ACCESS_TOKEN" | jq -r ".[0].id"
)

Set an email on the service account user that matches a row in your org structure file, so automatic user provisioning can link the principal it creates to that row:

curl -X PUT "$NGROK_HOST/admin/realms/master/users/$KEYCLOAK_SERVICE_ACCOUNT_USER_ID" \
     --no-progress-meter --fail-with-body  \
     -H "Authorization: Bearer $ADMIN_ACCESS_TOKEN"\
     -H "Content-Type: application/json" \
     --json '{
       "email": "jordan.lee@example.com",
       "emailVerified": true
     }'

This client has one service account, so every token it issues carries the same sub and email. Every request authenticated through it resolves to the same principal, Jordan Lee. A real deployment authenticates each caller with their own token instead, so each one resolves to their own principal.

Automatic user provisioning creates a Kong Identity principal from any OIDC provider’s token the first time its caller authenticates, without needing to set up a Kong Identity directory, auth server, or client manually. Every usage event’s subject resolves to principal/PRINCIPAL_UUID.

AI Cost Management attributes usage in two independent tracks: the subject and tags, which record context like project or team through a separate mechanism. This guide covers subject attribution only. See Tags and headers for the other track.

This guide attributes usage to a principal built from your own OIDC provider.

Add a trusted IdP

A trusted IdP is the OIDC issuer Konnect verifies tokens against. Mapping the token’s email claim lets a newly authenticated caller match an existing principal from your org chart, instead of creating an unlinked one.

Add a trusted IdP through the Konnect UI:

  1. In the Konnect sidebar, click Access Management.
  2. Click Identity Providers.
  3. Click New identity provider if this is your first IdP, or Add trusted IdP if you already have one.
  4. In the Name field, enter a label for this IdP, for example My OIDC Provider.
  5. In the Issuer URL field, enter your issuer URL (run echo $OIDC_ISSUER_URL to print the value you exported in the prerequisites).
  6. Enable Automatic user provisioning.
  7. In the User provisioning claim mapping section, enable Set email.
  8. In the Claim name field, enter email.
  9. Click Add IdP.

In this example, we’re using email because the Keycloak setup prerequisite sets an email attribute on the service account. This matches the email column in your org structure file. Without a matching email claim, automatic user provisioning still creates a principal, but it won’t link to an existing org chart user.

Upload an org structure (Optional)

AI Cost Management matches each automatically provisioned principal against your organization’s reporting structure. Upload an org chart if you want spend to roll up to a cost center, user, or team. If you skip this step, the principal is still created and the usage event still gets a subject, just without that reporting data.

In production, you’ll export this file from your HR system (HRIS). The file must be in CSV format and a maximum of 10 MB.

For this example, we’ll create a small CSV file directly, then upload it with kongctl import.

The kongctl import command is available starting in kongctl 1.27.0.

Create a file named org-structure.csv:

cat <<EOF > org-structure.csv
external_id,email,given_name,family_name,manager_external_id,cost_center
EMP1001,jordan.lee@example.com,Jordan,Lee,,ENG-100
EMP1002,alex.morgan@example.com,Alex,Morgan,EMP1001,ENG-100
EMP1003,sam.rivera@example.com,Sam,Rivera,EMP1001,ENG-100
EMP1004,taylor.kim@example.com,Taylor,Kim,EMP1001,ENG-100
EMP1005,casey.nguyen@example.com,Casey,Nguyen,EMP1001,ENG-100
EOF

Apply the CSV to the default Kong Identity directory:

kongctl import identity org-chart \
  --pat "$KONNECT_TOKEN" \
  --file org-structure.csv \
  --execute \
  --report-output-dir ./import-reports

You can set --dry-run instead of --execute to preview the import without changing any existing users or teams. See Org chart in AI Cost Management for the full column reference and import behavior.

Set a budget

A budget in AI Cost Management tracks spend against a limit and alerts you as spend grows.

Create a monthly budget with a $100 limit:

BUDGET_ID=$(curl -X POST "https://us.api.konghq.com/v1/ai-cost-management/budgets" \
     --no-progress-meter --fail-with-body  \
     -H "Authorization: Bearer $KONNECT_TOKEN" \
     --json '{
       "name": "monthly-org-budget",
       "effect": "limit",
       "scope": {
         "filters": []
       },
       "limit": {
         "value": "100",
         "currency": "USD"
       },
       "window": {
         "type": "fixed",
         "interval": "P1M",
         "anchored_at": "2026-01-01T00:00:00+00:00[UTC]"
       }
     }' | jq -r ".id"
)

The scope.filters empty array means this budget covers all organization-wide usage.

Create an AI Model Provider, AI Auth Strategy, and AI Model

Create an AI Model Provider to connect AI Gateway to OpenAI, an openid-connect AI Auth Strategy that verifies bearer tokens against your trusted IdP and forwards claims for provisioning, and an AI Model that references both:

kongctl apply -f - --auto-approve --pat "$KONNECT_TOKEN" << 'EOF'
ai_gateway_model_providers:
  - ref: openai-provider
    ai_gateway: !lookup {id: !env AI_GATEWAY_ID}
    name: openai-provider
    display_name: "OpenAI"
    type: openai
    config:
      auth:
        type: basic
        headers:
          - name: Authorization
            value: !secret {source: !env OPENAI_AUTH_HEADER}
ai_gateway_auth_strategies:
  - ref: oidc-attribution
    ai_gateway: !lookup {id: !env AI_GATEWAY_ID}
    name: oidc-attribution
    display_name: "OIDC Attribution"
    type: openid-connect
    config:
      issuer: !env OIDC_ISSUER_URL
      auth_methods:
        - bearer
      principals:
        enabled: true
        jit:
          all_claims: true
      cache_tokens_salt: oidc-attribution-cache-salt
ai_gateway_models:
  - ref: openai-chat
    ai_gateway: !lookup {id: !env AI_GATEWAY_ID}
    name: openai-chat
    display_name: "OpenAI Chat"
    type: model
    formats:
      - type: openai
    capabilities:
      - generate
    config:
      route:
        paths:
          - /v1
        model:
          body_param: model
          values:
            - openai-chat
    targets:
      - name: gpt-5.4-nano
        provider: !ref openai-provider#name
        config:
          type: openai
    access:
      auth_strategies:
        - !ref oidc-attribution#name
    policies: []
EOF

In this configuration example:

  • The strategy’s principals.jit.all_claims field forwards every token claim to the provisioning lookup, including the email claim you mapped on the trusted IdP.
  • The target has no input_cost or output_cost set, so AI Cost Management falls back to the model’s list price from the price catalog.

Send a request

Get an access token from your OIDC provider, then send a chat completion to generate a usage event. The auth strategy verifies the bearer token and resolves it to a principal, creating one automatically from the token’s forwarded claims if none matches yet.

Request an access token using the client credentials grant. /protocol/openid-connect/token is Keycloak’s token endpoint path. Adjust it if you’re using a different provider:

ACCESS_TOKEN=$(curl -X POST "$OIDC_ISSUER_URL/protocol/openid-connect/token" \
     --no-progress-meter --fail-with-body  \
     -H "Content-Type: application/x-www-form-urlencoded" \
     -d "grant_type=client_credentials" \
     -d "client_id=$OIDC_CLIENT_ID" \
     -d "client_secret=$OIDC_CLIENT_SECRET"  | jq -r ".access_token"
)

Use the access token to send a chat completion, which generates the usage event:

curl -X POST "$KONNECT_PROXY_URL/v1/chat/completions" \
     --no-progress-meter --fail-with-body  \
     -H "Content-Type: application/json"\
     -H "Authorization: Bearer $ACCESS_TOKEN" \
     --json '{
       "model": "openai-chat",
       "messages": [
         {
           "role": "user",
           "content": "What is an API gateway?"
         }
       ]
     }'

Validate

The events API returns the usage events for your organization, sorted by newest first. Find the event your request generated. If your org has other traffic, check that time matches when you sent the request:

curl -s "$KONNECT_CONTROL_PLANE_URL/v1/ai-cost-management/events" \
  -H "Authorization: Bearer $KONNECT_TOKEN" \
  | jq '.data[0] | {time, subject, context: .data.context, cost: .data.reported_cost}'

Check the following in the response:

  • subject shows your principal as principal/PRINCIPAL_UUID.
  • cost.value is greater than 0, using the model’s list price from the price catalog.

If cost.value is 0 or subject is absent, see Troubleshoot missing or wrong data.

You can also check this in the Konnect UI:

  1. In the sidebar, click Cost Management.
  2. Click Dashboard to see your request reflected in overall spend.
  3. Click Explorer to see spend, requests, or tokens over time for this model.
  4. Click Events debugger to find the individual event and open its full details.

What’s next

You can now:

Cleanup

To clean up all AI Gateway resources created in this guide, run:

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

In the Konnect sidebar, click Access Management, then click Identity Providers, and delete the trusted IdP you created.

Delete the budget you created:

curl -X DELETE "$KONNECT_CONTROL_PLANE_URL/v1/ai-cost-management/budgets/$BUDGET_ID" \
  -H "Authorization: Bearer $KONNECT_TOKEN"

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!