Skip to main content
Version: 1.11.0

JWT Authentication

AISIX can authenticate callers with short-lived JSON Web Tokens (JWTs) instead of long-lived caller API keys. A trust provider verifies each token against a JSON Web Key Set (JWKS) or a shared secret.

Each verified identity maps to a caller API key and inherits its model access, rate limits, and usage attribution. In AISIX Enterprise and AISIX Cloud, matching budgets also apply.

JWKS-based providers include Keycloak, Entra ID, Okta, Auth0, and other OIDC-compliant identity providers. AISIX can also verify HMAC-signed tokens from an issuer that shares a secret with the gateway. In both cases, AISIX verifies the token's signature and claims on every request. The agent does not need the caller API key's plaintext value.

Dashboard single sign-on for human operators and gateway JWT authentication for agent requests are independent. Configuring one does not affect the other.

How It Works​

When an environment has at least one enabled trust provider, AISIX inspects each request's bearer token:

  1. The JWT's issuer claim selects an enabled trust provider. An issuer match must be exact. Provider Selection describes the fallback rules for shared-secret providers that do not pin an issuer.
  2. AISIX verifies the token's signature against the provider's JSON Web Key Set (JWKS), or against its shared secret when the provider has one, and validates the registered claims: exp (expiration, always required), aud (audience, when the provider configures accepted audiences), and nbf (not-before) when present.
  3. The provider's required_scopes and bound_claims requirements are enforced.
  4. The provider's identity claim, sub by default, selects a caller key with the same subject and provider binding. The request then runs as that key. Binding both values prevents another trusted provider from asserting the same identity.
  5. If no key binds the identity directly, claim mappings can select an existing policy key from the verified claims. A token matching neither a binding nor a mapping is rejected.

AISIX rejects tokens that fail verification or do not map to a caller API key before the request reaches a provider, MCP server, or vector store. For a JWKS provider, signing-key rotation at the identity provider is picked up automatically, with no gateway restart.

Prerequisites​

Before starting, prepare the following:

  • One of these configuration paths:
    • AISIX Enterprise or AISIX Cloud with an environment and an attached gateway. Dashboard users need permission to manage OIDC providers and caller API keys. Admin API users need a write-scoped token from an identity with the same provider and API-key permissions. For AISIX Enterprise, follow the AISIX Enterprise getting-started guide. To request AISIX Cloud access, contact API7.
    • An open-source AISIX gateway that loads a declarative resources.yaml file.
  • A system that issues JWT tokens to your agents, with the verification material for the method it uses:
    • For JWKS verification, prepare the expected issuer and either its JWKS endpoint URL or its OIDC discovery document (<issuer>/.well-known/openid-configuration).
    • Ensure that a JWKS provider signs tokens with an asymmetric algorithm supported by AISIX: RSA (RS256, RS384, RS512, PS256, PS384, or PS512), ECDSA (ES256 or ES384), or EdDSA. AISIX rejects HMAC-signed tokens from a JWKS provider.
    • For HMAC signing, prepare the shared secret. It must contain at least 32 UTF-8 bytes. The expected issuer and audiences are optional. Configure this method as described in Shared-Secret (HMAC) Providers.
  • A model alias the caller should be allowed to use and, for the Admin API workflow, its model ID. If you have not created one yet, configure Provider Keys and Model Aliases first.
  • curl and jq. The open-source AISIX gateway also requires OpenSSL for the credential-generation command shown below.

Configure JWT Authentication​

Configure the trust provider and identity-bound caller API key using the management path for your deployment. Replace the example issuer, audience, subject, and model values with those from your issuing system and gateway.

Register the provider and bind the caller key in the same environment.

Open the environment and select OIDC providers, then New OIDC provider.

  1. Keep JWKS / OIDC discovery under Verification method.
  2. Set Name to corp-keycloak and Issuer URL to https://sso.example.com/realms/agents.
  3. Enter aisix-gateway in Audiences. Leave JWKS URL empty to use the issuer's discovery document.
JWKS verification with the provider name, issuer, audience, and discovery settings
  1. Keep the default Identity claim of sub. Enter ai.access in Required scopes (optional).
  2. Under Bound claims (optional), select Add bound claim. Enter department as the claim and ai-lab as the accepted value.
Identity claim, scope requirement, clock skew, and department bound claim
  1. Select Create provider. Confirm that the saved provider is enabled and shows the intended issuer and requirements.
Saved corp-keycloak trust provider and its verification requirements

Bind the caller identity:

  1. Open API keys. Select New API key to create billing-agent, or Edit on an existing key.
  2. For a new key or an existing selected-model key, select the model under Allowed models, retaining any other required access. An existing all-model key already grants it; keep that mode unchanged.
  3. Set JWT subject to agent-billing-01 and JWT provider to corp-keycloak together.
Caller API key bound to a subject and its trusted provider
  1. Select Create API key or Save changes. For a new key, save its plaintext if it will also be used for API-key authentication, then dismiss One-time view. JWT callers do not need that plaintext value.

To remove an existing binding, clear JWT subject, select Any enabled provider under JWT provider, and select Save changes. Both fields must be cleared together.

For an explicit signing-key endpoint, edit the provider and fill JWKS URL. Use this when discovery is unavailable or the keys are hosted on another origin:

Explicit JWKS URL for keys hosted on another origin

Authenticate a Request​

Have the agent obtain a token from the issuing system. Set the model alias and token, then send the token on the proxy API exactly like a caller API key:

# AISIX_PROXY is the gateway origin; omit a trailing slash and endpoint path.
# The local quickstarts use http://127.0.0.1:3000.
export AISIX_PROXY="YOUR_AISIX_GATEWAY_URL"
export MODEL_ALIAS="YOUR_MODEL_ALIAS"
export AGENT_JWT="YOUR_AGENT_JWT"

curl -sS -X POST "$AISIX_PROXY/v1/chat/completions" \
-H "Authorization: Bearer $AGENT_JWT" \
-H "Content-Type: application/json" \
-d '{
"model": "'"$MODEL_ALIAS"'",
"messages": [{"role": "user", "content": "Hello"}]
}' | jq

AISIX verifies the token and maps it to the billing-agent key: its sub claim agent-billing-01 matches the key's jwt_subject, and the token's issuer resolves to the corp-keycloak provider named in the key's jwt_provider. The request then runs under that key's permissions. The token's aud must include aisix-gateway. It must also carry the ai.access scope and the department: ai-lab claim required by the provider.

Shared-Secret (HMAC) Providers​

Some issuers sign tokens with a secret both sides hold rather than with a key pair published in a JWKS. Give the trust provider an hmac_secret to verify those tokens. The field is optional, and setting it changes how that one provider works:

  • Tokens are accepted only under HS256, HS384, or HS512.
  • Nothing is fetched: there is no JWKS request and no OIDC discovery. jwks_uri must not be set.
  • issuer and audiences become optional. When issuer is set, iss must match it. A nonempty audiences list requires aud to contain a listed value. Omitting either field skips that check; an empty audience list also skips audience validation.

Everything else behaves as it does for a JWKS provider. The exp claim remains mandatory. Identity claims, scope and claim requirements, claim mappings, clock-skew allowance, and caller-key bindings work the same way.

A provider without hmac_secret is unchanged: it fetches signing keys, accepts only the asymmetric algorithms listed under Prerequisites, and rejects HMAC-signed tokens.

Prefer asymmetric signing where you can

With a shared secret, the gateway holds a key that can also mint tokens. Leaking it allows an attacker to impersonate any identity the issuer can assert. Use a JWKS provider whenever the issuer can offer one. For the open-source AISIX gateway, keep the secret out of the file by referencing an environment variable.

Secret Handling​

The secret's UTF-8 bytes are the HMAC key as-is. Nothing is base64-decoded or derived, so the issuer must sign with exactly the same byte string. The secret must be at least 32 bytes long.

A provider holds one secret. Rotate by updating the secret on the provider; tokens signed with the previous secret stop verifying as soon as the change reaches the gateway.

Configure a Shared-Secret Provider​

Create the provider in the environment serving the application:

  1. Open OIDC providers and select New OIDC provider.
  2. Choose Shared secret (HMAC) under Verification method. Set Name to partner-hmac and enter a Shared secret of at least 32 UTF-8 bytes.
HMAC verification selected with a write-only shared secret
  1. Add any issuer, audience, scope, or bound-claim requirements. This example keeps the ai.access scope and leaves issuer and audiences unset.
  2. Select Create provider.

Bind a caller identity to the new provider:

  1. Open API keys and create or edit the caller key. For a new key, select its model under Allowed models; retain required access on an existing key.
  2. Set JWT subject to partner-agent-01 and JWT provider to partner-hmac together.
Caller identity bound to the partner-hmac provider
  1. Select Create API key or Save changes. For a new key, handle its one-time plaintext as described in the initial binding procedure. JWT callers do not need it.

The secret is never returned. On later edits, leave Shared secret blank to retain it, or enter a replacement and select Save changes to rotate it.

Editing an HMAC provider whose stored secret is not displayed

To switch the provider to JWKS, select JWKS / OIDC discovery, then enter Issuer URL and at least one value in Audiences. Saving this change clears the stored HMAC secret.

HMAC provider switched to JWKS with issuer and audience supplied

Select Save changes.

Verify the HMAC Identity​

Have the issuing system sign a token with the configured shared secret. With the default identity claim and this example's requirements, include:

ClaimValue
subpartner-agent-01
scopeai.access
expA future expiration timestamp

If you configured an issuer or audience, the token must satisfy those values too. Send this token using Authenticate a Request. It resolves through partner-hmac to the partner-agent caller key.

Provider Selection​

When a token's iss matches exactly one enabled provider's issuer, that provider alone verifies the token. A mismatch of mode or algorithm there is a 401, with no fallback to another provider.

When no enabled provider matches the issuer, AISIX tries issuer-less shared-secret providers in name order. The first provider that verifies the token wins. AISIX rejects the token if none succeeds. JWKS providers are never candidates because they require an issuer.

Give each issuer-less shared-secret provider a distinct secret. When a token passes signature and registered-claim checks for several of these providers, the first in name order wins. Only that provider's scope, bound-claim, and identity policies apply.

Configuration Errors​

AISIX rejects a provider that is configured inconsistently:

  • jwks_uri set together with hmac_secret.
  • A provider without hmac_secret that lacks an issuer or at least one audience.
  • An hmac_secret shorter than 32 bytes.

The AISIX Cloud Admin API answers 400 for each of these. In a resources file, the offending entry is rejected at load, reported by Configuration Status and counted in aisix_config_rejected_resources.

Key Rotation​

This section covers providers verified against a JWKS. A shared-secret provider fetches nothing, so it is rotated by updating its hmac_secret.

When your identity provider introduces a signing key, an unrecognized key ID triggers a JWKS refresh. No configuration change or gateway restart is needed.

AISIX coalesces simultaneous outbound fetches for the same OIDC discovery document or JWKS URL. Requests wait for the shared fetch when the cache is empty, the configured JWKS URL has changed, or a token uses a newly rotated key. Requests that can use a stale cached result continue while the refresh runs.

After a fetch completes, successfully or unsuccessfully, AISIX waits at least one second before fetching the same discovery document or JWKS URL again. A request that needs new trust material during this interval may need to be retried.

AISIX treats cached discovery results and key sets as fresh for 10 minutes. The next authentication request after that interval triggers a refresh. Once the refreshed set omits a retired key, tokens signed by it stop authenticating.

If discovery or JWKS is unavailable, AISIX keeps the last successful result. Existing tokens can continue authenticating, but a retired key remains trusted until a later refresh succeeds.

Update or Remove a Trust Provider​

Provider updates change which tokens the gateway trusts. Disable a provider to suspend verification, or delete it to remove its trust configuration.

Use the dashboard or Admin API to change the existing provider.

  1. Open OIDC providers and select Edit on the provider.
  2. Change the required fields. Changing the issuer or identity claim shows a warning because it disconnects affected per-user MCP sign-ins, as described below.
Issuer edit warning about affected per-user sign-ins
  1. Review the warning, then select Save changes.

Select Disable to pause JWT verification while retaining the provider, or Enable to resume it.

Trust provider retained in a disabled state

Select Delete and confirm to remove the provider. Existing key bindings and claim mappings remain configured but cannot resolve through it until a provider with that name exists again.

Choose Trust Provider Settings​

The verification method determines which issuer, audience, and key settings apply:

FieldDescription
issuerExpected iss claim, compared exactly against the token. The control plane enforces uniqueness within an environment. In format-2 resources files, keep issuer values distinct among enabled providers: duplicate issuers can load, but tokens for that issuer fail authentication. It is required for JWKS verification and optional with hmac_secret; an issuer-less shared-secret provider does not check iss.
audiencesAccepted aud values. JWKS verification requires at least one, and the token must contain a match. With hmac_secret, omit the field or use an empty list to skip audience validation.
jwks_uriEndpoint the signing keys are fetched from. Omit it to resolve the endpoint from the issuer's OIDC discovery document. It must not be set together with hmac_secret.
hmac_secretShared secret that switches the provider to HMAC verification. Omit it for a provider verified against a JWKS. See Shared-Secret (HMAC) Providers.
identity_claimClaim path whose value selects the caller API key, matched against each key's jwt_subject, for example resource_access.account. Defaults to sub.
required_scopesScopes that must all be present in the token's scope claim (a space-delimited string or an array).
bound_claimsAdditional claim requirements. Each key is a claim path. A string claim must equal one of the expected values; an array claim must contain one of them.
tag_claimsCost attribution tags read from the verified token on each request, as an object of tag key to claim path, for example {"department": "department", "subsidiary": "org.subsidiary"}. Per tag key, a value read this way takes precedence over the caller API key, its team, and its member. Keys match ^[a-z][a-z0-9_]{0,62}$, paths are non-empty, and at most 32 entries are allowed. In AISIX Enterprise and AISIX Cloud, each key must be declared in the organization. Requires a gateway at 1.9.0 or later. See Read Tags From JWT Claims.
leeway_secsClock-skew allowance from 0 to 300 seconds for the time-based claims. Defaults to 0.
loginThe OAuth client (client_id, optional client_secret and scopes) the gateway signs users in with, for MCP clients configured with only a URL. It cannot be set with hmac_secret. Configure it on only one enabled provider in the environment. Multiple login providers can load from a format-2 file, but MCP sign-in fails. See Interactive MCP Sign-In.
enabledWhether the provider participates in authentication. Defaults to true.
URL user information is not a protected secret

User information in issuer or jwks_uri (user:password@) is accepted and used as written. In AISIX Enterprise and AISIX Cloud, AISIX Cloud Admin API responses include these URLs and audit records store them as configured. Gateway logs can also include the issuer.

Prefer credential-free HTTPS endpoints or network-level access controls.

For a JWKS provider, omitting jwks_uri makes AISIX resolve and cache the signing-key endpoint from the issuer's discovery document. Discovery requires the document's issuer to match exactly and its advertised JWKS URL to use the same origin as the issuer. Provide jwks_uri explicitly when discovery is unreachable or the signing keys are hosted on another origin.

Claim Paths​

identity_claim, bound_claims, tag_claims, and claim-mapping conditions use the same claim-path syntax.

A claim path can match a top-level claim name or use dot notation to select a nested value. For example, https://example.com/department can match a top-level claim with that exact name, while resource_access.account can select account from the resource_access claim.

If both interpretations are possible, the exact top-level claim name takes precedence. For example, a.b matches a top-level a.b claim before the nested b value under a.

Gateways earlier than 1.9.0 support only nested dot notation and cannot match top-level claim names containing periods.

Rejection Reasons​

On OpenAI-style proxy routes, a rejected token carries a stable error.code so clients can react without parsing messages. Anthropic-style routes omit code and use the HTTP status and Anthropic-compatible error.type; see Headers and Error Codes.

OpenAI-style error.codeHTTP statusMeaning
jwt_expired401The token's exp deadline has passed. Fetch a fresh token.
jwt_invalid401The token is malformed or fails issuer, signature, signing algorithm, audience, required-claim, or not-before validation.
jwt_claims_rejected403The token is valid but does not satisfy the provider's required_scopes or bound_claims.
jwt_identity_unmapped401The configured identity claim is missing or is not a string, or the identity resolves to no key — no caller API key has matching jwt_provider and jwt_subject values and no claim mapping matched. Check the token claim, key binding, and mappings.
jwks_unavailable503AISIX could not resolve or fetch the provider's signing keys. Check the OIDC discovery or JWKS endpoint, then retry.

Next Steps​

  • JWT Claim Mappings: admit whole classes of identities — departments, groups, applications — through priority-ordered claim rules instead of per-identity bindings.
  • Keycloak Integration: a verified end-to-end walkthrough from a Keycloak realm to mapped, attributed requests.
  • Caller API Keys: manage the model access and other controls inherited by each mapped identity.
  • Cost Attribution Tags: attribute cost to values read from the token, such as a department.
  • API Key and Model Rate Limits: limit the request volume or token usage of JWT-authenticated callers.
  • Configuration Propagation: understand how configuration changes reach AISIX gateways.