Authenticating to a backend¶
How-to guideThe steps for one task.
Some backends want a token of their own, issued by their identity provider, not the caller's. The typical case:
- A mobile app signs in with your provider (XXAuth) and gets a JWT.
- The employees API belongs to a partner (YYAPI) that only accepts tokens from its provider (YYAuth), obtained with client credentials the app must never hold.
- YYAPI wants to know which employee is calling, from a claim in the XX token.
The gateway does the handshake. Three policies on the API, in this order:
apiVersion: apinx/v1
kind: API
name: employees
base_path: /yy
upstream: yy-api
strip_prefix: true
policies:
# 1. The caller's token, validated against your provider's published keys.
- type: jwt
config:
issuer: https://xxauth.example.com/
jwks_url: https://xxauth.example.com/.well-known/jwks.json
audiences: [mobile-xx]
required_claims:
employee_id: [] # must be present; whichever claim carries the user
strip: true # the XX token never reaches the partner
# 2. The gateway's own token for the partner.
- type: upstream-auth
config:
token_url: https://yyauth.example.com/oauth/token
client_id: gateway-xx
client_secret: ${secret} # stored encrypted
scopes: [employees:read]
headers:
X-User-Id: ${claim.employee_id}
X-Dept: ${claim.profile.dept} # dotted path for nested claims
operations:
- name: all
path: /{rest...}
What happens per request¶
jwtverifies the XX token locally against XXAuth's keys (fetched once, cached), checks the required claim, and strips the token.upstream-authsetsAuthorization: Bearer <yy-token>from its cache. YYAuth is called only when no token is cached or the token is stale: withinrefresh_before(30 s) of expiry, or with no more thanrefresh_before_percentof its lifetime left. Concurrent requests wait for one call. The extra headers are filled from the caller's claims.- The request reaches YYAPI with the YY token and
X-User-Id, and without the XX token.
Behaviour under failure¶
| Situation | Behaviour |
|---|---|
| YYAPI answers 401 | The cached token is discarded; the next request fetches a fresh one |
| YYAuth is down, a valid token is cached | The token keeps serving |
| YYAuth is down, nothing valid is cached | 502 APX-PL-0026, nothing forwarded without credentials |
| The XX token lacks the required claim | 403 at the gateway; YYAuth is not called |
A backend with its own login endpoint¶
Many backends are not OAuth 2 providers: they have a POST /login that takes a JSON body and
answers with a JSON document holding a JWT. The same policy handles them with request: json:
policies:
- type: upstream-auth
config:
token_url: https://hr.example.com/api/auth/login
request: json # a JSON body instead of OAuth 2 form fields
grant: password
username: svc-gateway # a service account the backend knows
password: ${secret} # stored encrypted
username_field: username # the JSON field names, when they differ
password_field: password
token_field: accessToken # where the token is; dotted for nested, e.g. data.accessToken
expires_field: expiresIn # lifetime in seconds; absent, the token's exp claim decides
params:
deviceId: gateway # any extra fields the login wants
The gateway posts {"username":"svc-gateway","password":"…","deviceId":"gateway"}, reads the
token from accessToken, caches it until expiresIn seconds minus refresh_before, and sends
it to the backend as Authorization: Bearer …. client_id and client_secret are not needed;
when the backend wants them too, set them and they are sent as JSON fields (or in HTTP Basic
with client_auth: basic). The caller's identity goes to the backend in headers, as above.
The YAML samples walk through one call end to end.
The token goes to the backend only¶
The token is fetched for this route's backend and is sent nowhere else. A service callout
that forwards Authorization forwards the caller's header, never the token this policy put
in its place, and a mirror copy leaves
without it unless the route sets mirror.backend_credentials: true. Traces show it redacted.
Caching, renewal and refresh tokens¶
A token is cached for its lifetime (expires_in, else the JWT's exp, else cache_ttl) and
renewed a little early so that no request forwards a token about to expire. Two settings say
how early; the larger wins:
refresh_before: a fixed margin, 30 s by default.refresh_before_percent: a share of the lifetime.20renews a 30-minute token after 24 minutes, a 2-minute token after 96 seconds.
When the endpoint gives a refresh token, renewal uses it instead of the credentials:
grant_type=refresh_token against an OAuth 2 endpoint, or a JSON body with the refresh token
against a login API (refresh_url when the backend has a separate endpoint for it). A refused
refresh (expired or revoked, 400 invalid_grant) falls back to the credentials at once, so a
request never fails because a refresh token aged out. A refresh answer that carries a new refresh
token replaces the old one (rotation); one that does not keeps it.
# OAuth 2 with refresh tokens (Keycloak, Auth0, Azure AD and the like).
- type: upstream-auth
config:
token_url: https://login.example.com/realms/hr/protocol/openid-connect/token
grant: password
client_id: apinx-gateway
client_secret: ${secret}
username: svc-gateway
password: ${secret}
scopes: [openid, employees:read]
refresh_before_percent: 20 # renew at 80% of the lifetime
refresh_before: 30s # and never later than 30 s before expiry
# refresh_token_field: refresh_token (the default; empty disables refresh tokens)
# A login API with its own refresh endpoint and field names.
- type: upstream-auth
config:
token_url: https://hr.example.com/api/auth/login
refresh_url: https://hr.example.com/api/auth/refresh
request: json
grant: password
username: svc-gateway
password: ${secret}
token_field: accessToken
expires_field: expiresIn
refresh_token_field: refreshToken # read from the answer, sent as {"refreshToken": "…"}
refresh_before_percent: 20
The trace step reads "cached token", "token renewed with the refresh token" or "token fetched from the backend's token endpoint", so the inspector shows which road each request took.
Grants and providers¶
| Setting | Options |
|---|---|
request |
form (default): an OAuth 2 token endpoint. json: the backend's own login endpoint, see above |
grant |
client_credentials (default): a token for the gateway itself. password: a service account's username and password with the client credentials |
client_auth |
basic (default, RFC 6749) or body (client id and secret as form fields) |
audience, params |
Extra token-endpoint parameters for Auth0, Keycloak and similar |
header, prefix |
Where and how the token is sent; default Authorization: Bearer … |
cache_ttl |
Used when the endpoint gives no expires_in and the token has no exp claim |
refresh_before, refresh_before_percent |
How early a token is renewed: a fixed margin, a share of the lifetime, or both (the larger wins) |
refresh_token_field, refresh_url |
Renewal with a refresh token when the endpoint gives one; the field name in the answer and the request, and a separate refresh endpoint if the backend has one |
Ten routes to the same partner share one token: the cache is keyed by endpoint, client, account, scopes and a fingerprint of the secret, and survives redeploys. Two bindings that differ only in their secret never share a token.
What is never exposed¶
- The client secret is a sealed field: encrypted in the store, absent from exports, audit and the trace.
- The backend token is marked sensitive and redacted in the request inspector.
- The step appears in the trace as "cached token" or "token fetched", with its duration.