Set up Kong Identity attribution for AI Cost Management

TL;DR

Upload your organization’s structure, then create an openid-connect AI Auth Strategy with principals.enabled set to true and attach it to the AI Model. The first authenticated request creates a matching principal automatically, and the usage event’s subject is recorded 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.29.0).

  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"

A directory is a regional collection of principals. A Konnect organization supports only one Kong Identity directory. Create a directory for the tutorial, or look up your existing one.

You need a Kong Identity auth server and client application to authenticate requests.

A client requests a token under an OAuth2 scope. Configure one using the /v1/auth-servers/$AUTH_SERVER_ID/scopes endpoint, so the client and the AI Auth Strategy can both be granted it:

SCOPE_ID=$(curl -X POST "https://us.api.konghq.com/v1/auth-servers/$AUTH_SERVER_ID/scopes" \
     --no-progress-meter --fail-with-body  \
     -H "Authorization: Bearer $KONNECT_TOKEN" \
     --json '{
       "name": "ai-cost-management-access",
       "description": "Scope for AI Cost Management attribution clients",
       "default": false,
       "include_in_metadata": false,
       "enabled": true
     }' | jq -r ".id"
)

A client’s secret is only returned once, at creation, so this guide creates a new client rather than reusing one whose secret you might not have saved.

Create a client using the /v1/auth-servers/$AUTH_SERVER_ID/clients endpoint:

_response=$(curl -X POST "https://us.api.konghq.com/v1/auth-servers/$AUTH_SERVER_ID/clients" \
     --no-progress-meter --fail-with-body  \
     -H "Authorization: Bearer $KONNECT_TOKEN" \
     --json '{
       "name": "ai-cost-management-kong-identity-client",
       "allow_all_scopes": false,
       "allow_scopes": [
         "'$SCOPE_ID'"
       ],
       "access_token_duration": 300,
       "grant_types": [
         "client_credentials"
       ],
       "response_types": [
         "token"
       ],
       "redirect_uris": [],
       "login_uri": ""
     }')

Export the env variables:

export CLIENT_ID=$(echo "$_response" | jq -r ".id")
export CLIENT_SECRET=$(echo "$_response" | jq -r ".client_secret")

Kong Identity attribution links each AI request to a Kong Identity principal.

Every usage event’s subject resolves to principal/PRINCIPAL_UUID. The AI Cost Management dashboard, explorer, and events debugger show the event by the principal’s display name.

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 Kong Identity’s own auth server.

Add a trusted IdP

A trusted IdP is the OIDC issuer Konnect verifies tokens against, and the place you turn on automatic user provisioning for that issuer. Kong Identity’s own auth server is a valid issuer, so add it as a trusted IdP:

  1. In the Konnect sidebar, click Access Management.
  2. Click Identity Providers.
  3. Click Add trusted IdP.
  4. In the Name field, enter a label for this IdP, for example Kong Identity.
  5. In the Issuer URL field, enter your issuer URL (run echo $ISSUER_URL to print the value you exported earlier).
  6. Enable Automatic user provisioning.
  7. Click Add IdP.

A client credentials token includes only a sub claim, so this guide skips claim mapping. For an interactive sign-in flow, your provider’s token can include richer claims.

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.

The org structure file must be in CSV format and a maximum of 10 MB. Choose whether to use an export from your HR system (HRIS) or a sample file:

The kongctl import command is available starting in kongctl 1.27.0.

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 Kong Identity issuer and enables principal lookup, and an AI Model that references both.

When a request arrives, AI Gateway verifies the bearer token and looks up the principal whose identity matches the token’s sub claim, then records it as the event’s subject. If no principal matches yet, Kong Identity creates one from the token, using the trusted IdP and automatic user provisioning you just set up.

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: kong-identity-oidc
    ai_gateway: !lookup {id: !env AI_GATEWAY_ID}
    name: kong-identity-oidc
    display_name: "Kong Identity OIDC"
    type: openid-connect
    config:
      issuer: !env ISSUER_URL
      auth_methods:
        - bearer
      principals:
        enabled: true
      scopes:
        - ai-cost-management-access
      cache_tokens_salt: kong-identity-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 kong-identity-oidc#name
    policies: []
EOF

The target doesn’t set input_cost or output_cost, 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 Kong Identity issuer, then send a chat completion to generate a usage event. The auth strategy verifies the token and resolves it to a principal, creating one automatically from the token if none matches yet.

Request an access token using the client credentials grant:

ACCESS_TOKEN=$(curl -X POST "$ISSUER_URL/oauth/token" \
     --no-progress-meter --fail-with-body  \
     -H "Content-Type: application/x-www-form-urlencoded" \
     -d "grant_type=client_credentials" \
     -d "client_id=$CLIENT_ID" \
     -d "client_secret=$CLIENT_SECRET" \
     -d "scope=ai-cost-management-access"  | 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}'

The event should look like this:

{
  "time": "2026-11-12T19:02:02.695Z",
  "subject": "principal/01a1c15c-310d-79a6-acde-85f746946396",
  "context": {
    "provider": "openai",
    "model": "gpt-5.4-nano-2026-03-17",
    "model_id": "5382d282-c9d3-4c96-910e-76af70e3c883",
    "request_mode": "oneshot"
  },
  "cost": {
    "value": "0.000016",
    "currency": "USD"
  }
}

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"

FAQs

Yes. Create a principal in the Kong Identity directory, then link it to your client so AI Gateway can match the token’s sub claim to it, using POST /v2/directories/{directoryId}/principals and POST /v2/directories/{directoryId}/principals/{principalId}/identities. See Principals for details.

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!