JWT authentication and key mappings
JWT authentication lets services that already hold an access token from your identity provider call the gateway with that token instead of a Spanway virtual key. The gateway checks the token's signature against the provider's published keys, reads the claims inside it, and works out which team the request is billed to, which user it belongs to, and which routes and models it may use. Nobody issues or rotates a key for that service. When the identity provider disables the client it stops getting new tokens, and the tokens it already holds stop working when they expire, because the gateway checks the signature and the expiry and does not ask the provider about each token. Keep token lifetimes short, and set public_key_stale_ttl: 0 when you rotate a signing key out so the old key stops working at once.
JWT auth is part of Spanway Enterprise. On a gateway without a license, a request that carries a JWT is refused with 403 and virtual keys keep working as usual. For a client that can only send a virtual key, workload identity federation trades its OIDC token for a short-lived key instead. For opaque OAuth tokens that are not JWTs, see OAuth2 bearer validation.
A real-world scenario
A billing service runs in your cloud and gets an access token from Entra ID every hour. Its team wants it to call the gateway with that token so no Spanway key ever sits in the service's secrets. The platform admin turns on JWT auth, points the gateway at the tenant's discovery document, and maps the client_id claim to the billing team. Later, the finance team asks that the billing service behave exactly like one named virtual key with its own budget and guardrails, so the admin adds a JWT key mapping for the service's azp claim.
Steps
-
Turn on JWT auth in
config.yamland tell the gateway which claims name the team and user.general_settings:enable_jwt_auth: truespanway_jwtauth:team_id_jwt_field: client_iduser_id_jwt_field: subuser_email_jwt_field: emailuser_id_upsert: trueadmin_jwt_scope: spanway_proxy_admin -
Point the gateway at your identity provider and restrict which tokens it accepts, then restart it.
export JWT_PUBLIC_KEY_URL="https://login.example.com/.well-known/openid-configuration"export JWT_AUDIENCE="api://spanway"export JWT_ISSUER="https://login.example.com" -
Create the team the claim names. In the Admin UI open Teams, choose Create New Team, and give it the id the token carries,
billingin this example. The same works withPOST /team/new. -
Call the gateway with the service's access token.
curl -s http://localhost:4000/v1/chat/completions \-H "Authorization: Bearer $ACCESS_TOKEN" \-H "Content-Type: application/json" \-d '{"model": "claude-sonnet", "messages": [{"role": "user", "content": "Reconcile invoice 4411."}]}' -
To make the service behave as one specific virtual key, open Settings, Admin Settings, and the JWT Key Mappings tab. Choose + Create Mapping, enter the Claim Name (
azp), the Claim Value (billing-service), the Issuer, a Description, and under Identify the Key By paste the Virtual Key or its Key Hash. The same mapping through the API:curl -s -X POST http://localhost:4000/jwt/key/mapping/new \-H "Authorization: Bearer $SPANWAY_API_KEY" -H "Content-Type: application/json" \-d '{"jwt_claim_name": "azp", "jwt_claim_value": "billing-service", "key": "sk-billing", "jwt_issuer": "https://login.example.com", "description": "Billing service"}'Set
virtual_key_claim_field: azpunderspanway_jwtauthso the gateway knows which claim to look up.
Expected result
The chat completion in step 4 succeeds and appears in Logs under the billing team and the user named by sub. Spend accrues to that team on the Teams page. After step 5 the mapping is created and returned, and every request whose azp claim is billing-service runs as the key sk-billing, with that key's budget, models and guardrails.
{
"id": "jkm_01J...",
"jwt_issuer": "https://login.example.com",
"jwt_claim_name": "azp",
"jwt_claim_value": "billing-service",
"description": "Billing service",
"is_active": true,
"created_at": "2026-10-16T09:12:00Z",
"updated_at": "2026-10-16T09:12:00Z",
"created_by": "admin",
"updated_by": "admin"
}
How tokens are checked
JWT_PUBLIC_KEY_URL is the JWKS URL or an OpenID discovery document from which the JWKS URL is read. Keys are cached for public_key_ttl seconds (600) and kept usable for a further public_key_stale_ttl seconds (3600) when the provider is unreachable. Set that to 0 to fail closed. JWT_AUDIENCE and JWT_ISSUER scope which tokens are accepted, and the gateway logs a warning on the first JWT request when neither is set, because any token signed by the provider would then be accepted. Each entry under issuers needs an audience unless it sets disable_audience_validation: true. A bearer token that parses as a JWT is checked this way, anything else is treated as a virtual key.
Mapping claims
| Setting | Meaning |
|---|---|
team_id_jwt_field, team_ids_jwt_field, team_alias_jwt_field | Claim naming the team, or a list of teams, by id or alias. team_id_default applies when the claim is absent. |
user_id_jwt_field, user_email_jwt_field, user_id_upsert | Claim naming the internal user, and whether unknown users are created. Off by default, so a token for an unknown user is refused. |
team_id_upsert, upsert_sso_user_to_team | Off by default. team_id_upsert creates a team the first time a token names one that does not exist yet, and upsert_sso_user_to_team adds the user to the teams the token names. Off means unknown teams are refused and membership stays with admins. |
org_id_jwt_field, org_alias_jwt_field, end_user_id_jwt_field | Organization and end user attribution. |
user_allowed_email_domain | Reject users whose email is outside this domain. |
admin_jwt_scope, admin_allowed_routes, team_allowed_routes, public_allowed_routes | Route groups each kind of token may call. Defaults are the management, spend and info routes for admins, the OpenAI, info, MCP and Messages routes for teams, and public routes for everything else. |
roles_jwt_field, role_mappings, object_id_jwt_field, enforce_rbac | Map a claim value to an internal role (proxy_admin, team, internal_user and so on) and enforce role based access on every route. |
scope_mappings, enforce_scope_based_access | Grant models and routes per OAuth scope. |
user_roles_jwt_field, user_allowed_roles, jwt_spanway_role_map, sync_user_role_and_teams | Keep the user's role and teams in sync with the identity provider on each request. |
enforce_team_based_model_access | Only models granted to the team may be called. |
team_claim_fallback, fallback_to_db_teams | What to do when the team claim does not resolve: fall back to the caller's single team in the database, or to their database memberships. With fallback_to_db_teams a caller may also pick one of their teams with the x-spanway-team-id header. It needs user_id_upsert: true. |
agent_id_jwt_field | Claim naming a registered agent, such as azp for an Entra application token. |
mcp_client_id_jwt_field | Claim naming the MCP client application, checked against general_settings.mcp_allowed_clients. When set, MCP tool calls whose token carries the claim are also tagged MCP-Client: <label>, so MCP usage analytics can split active users and agents by client app. The claim alone turns the labels on, no allowlist is needed. |
oidc_userinfo_enabled, oidc_userinfo_endpoint, oidc_userinfo_cache_ttl | Used by the MCP token exchange to read identity from the UserInfo endpoint. On API routes a bearer token that is not a JWT goes to virtual key auth, so these settings do not change API route sign-in. |
public_key_ttl, public_key_stale_ttl | How long the provider's signing keys are cached (600 seconds) and kept usable while the provider is unreachable (3600 seconds). |
routing_overrides | Rules by iss, client_id, scope and aud that send matching tokens through the OAuth2 path instead of JWT auth. |
custom_validate | A function of your own that must return True for the token to be accepted. |
issuers | Per issuer JWKS URL, audience and claim mappings, used when a token's iss matches. Tokens from other issuers still use the global settings. |
To pick one of a caller's teams per request when fallback_to_db_teams is on:
curl -X POST http://localhost:4000/v1/chat/completions \
-H "Authorization: Bearer $JWT" -H "x-spanway-team-id: billing" -H "Content-Type: application/json" \
-d '{"model": "claude-haiku-5-5", "messages": [{"role": "user", "content": "Hello"}]}'
general_settings:
spanway_jwtauth:
issuers:
- issuer: https://login.example.com
jwks_url: https://login.example.com/discovery/keys
audience: api://spanway
team_ids_jwt_field: groups
- issuer: https://partner.example.org
jwks_url: https://partner.example.org/jwks
audience: spanway-partner
team_id_jwt_field: tenant
JWT key mappings
A JWT key mapping binds a claim value to a virtual key, so the JWT client gets that key's budget, models, guardrails and spend attribution.
general_settings:
spanway_jwtauth:
virtual_key_claim_field: azp
unregistered_jwt_client_behavior: reject
virtual_key_mapping_cache_ttl: 300
Pass exactly one of key, the plaintext key, or token, its SHA-256 hash. When a request's JWT carries the claim named in virtual_key_claim_field and a mapping exists for that value and issuer, the request runs as that virtual key. unregistered_jwt_client_behavior decides what happens when no mapping exists: fallback_team_mapping (the default) continues with team based JWT auth, reject returns 403, and auto_register creates a new virtual key and mapping on first contact. With auto_register_map_existing_key: true and a claim that identifies the user, the mapping points at a suitable key the user already owns instead of minting one. Lookups are cached for virtual_key_mapping_cache_ttl seconds.
Creating and updating mappings needs a proxy admin and an enterprise license, so an unlicensed gateway answers 403 instead of storing a mapping that would never apply. Listing, reading and deleting mappings stay open to proxy admins after a license lapses, so old mappings can be cleaned up. Every change is written to the audit log, including the key and mapping that auto_register creates, which show auto_register as the actor. The JWT key mappings page walks through the Admin UI tab step by step.
| Method | Path | Summary |
|---|---|---|
| POST | /jwt/key/mapping/delete | Delete a JWT key mapping |
| GET | /jwt/key/mapping/info | Get one JWT key mapping |
| GET | /jwt/key/mapping/list | List JWT key mappings |
| POST | /jwt/key/mapping/new | Map a JWT claim value to a virtual key |
| POST | /jwt/key/mapping/update | Change a JWT key mapping |
Admin UI
The JWT Key Mappings tab under Settings, Admin Settings lists mappings with their claim, issuer and Active status, creates them with + Create Mapping, and edits or deletes them from the row menu. A mapping can point at a plaintext key or its SHA-256 hash. The claim name and value cannot be changed after creation, so delete and recreate a mapping to move it to another claim. Proxy admin viewers see the tab read-only. Users and teams resolved from JWTs appear on the Internal Users and Teams pages, and spend attributed through a JWT shows up under the team and user the claims named.
Errors
| What you see | Why | Fix |
|---|---|---|
403 JWT Auth is an enterprise only feature | The gateway has no enterprise license. | Set the license key, see enterprise. Virtual keys keep working meanwhile. |
403 JWT key mappings only apply when JWT auth is on, and JWT auth needs a Spanway enterprise license. ... | A mapping was created or updated on a gateway without a license. | Add a license first. |
401 naming an invalid signature or key id. | The token was signed with a key the gateway cannot find at JWT_PUBLIC_KEY_URL. | Check the URL points at the issuer's discovery document or JWKS, and that the token is from that issuer. |
401 naming the audience or issuer. | JWT_AUDIENCE or JWT_ISSUER does not match the token's aud or iss. | Request the token for the audience the gateway expects, or fix the variable. |
401 Token Expired, type expired_key | The token is past its exp time. | Fetch a new token from the identity provider. |
503 Service Unavailable, the identity provider's JWKS endpoint is temporarily unreachable ..., type auth_provider_unavailable | The signing keys could not be fetched and the cached copy is older than public_key_stale_ttl. | Retry shortly, and check the gateway can reach the provider, see 503. |
404 Team doesn't exist in db. Team=<id>. Create team via `/team/new` call. | The claim named in team_id_jwt_field carries an id that is not a team. | Create the team with that id, or set team_id_upsert, team_id_default, team_claim_fallback or fallback_to_db_teams. |
403 Email domain not allowed. User email: <email>. Allowed domain: <domain> | user_allowed_email_domain is set and the token's email is outside it. | Use an account in the allowed domain, or change the setting. |
403 Invalid JWT token | Your custom_validate function returned something other than True. | Check the function and the token's claims. |
403 naming the route and the role | enforce_rbac is on and the token's role may not call this route. | Map the role in role_mappings, or widen the role's routes. |
403 Only proxy admins can create JWT key mappings | The caller of /jwt/key/mapping/new is not a proxy admin. | Use a proxy admin key. |
409 A mapping for claim ... already exists | A mapping with the same claim name, value and issuer exists. | Update the existing mapping with /jwt/key/mapping/update instead. |
400 The provided key does not match an existing virtual key | key or token names no virtual key. | Create the key first, or check the hash. |
Logs
| Level | Line | Meaning | Action |
|---|---|---|---|
| WARNING | JWT auth is enabled but neither JWT_AUDIENCE nor JWT_ISSUER is configured. ... | Logged once, on the first JWT request. Any token signed by the provider's keys is accepted. | Set JWT_AUDIENCE, and ideally JWT_ISSUER. |
| INFO | JWT Key Mapping (auto_register): ... | auto_register created a key and mapping for a new claim value. | Normal when auto registration is on. Review new mappings on the JWT Key Mappings tab. |
| WARNING | JWT Key Mapping (auto_register): failed to delete orphaned key after race: <reason> | Two first requests raced and the losing request's new key could not be removed. The key maps to nothing. | Delete the unused key on the Virtual Keys page. |
Related
- Workload identity federation for clients that can only send a virtual key.
- OAuth2 bearer validation for opaque OAuth tokens and the
routing_overridespath. - Team membership from SSO applies the same group claims at Admin UI sign-in.
- IP and route allow-lists for
admin_allowed_routes,team_allowed_routesandpublic_allowed_routes. - Agent identity providers lists which of these issuers can bind a registered agent.
- Custom authentication when you need your own check.