What is JWT propagation in microservices, and which two identities does every call carry?

JWT propagation in microservices means carrying the end user's identity from the edge, where a gateway first validates a token, through every internal hop that does work on that user's behalf. When the orders service calls billing, and billing calls a ledger service, each downstream service still needs to know whose request it is serving. Otherwise it cannot apply per-user rules or record who did what.

Every internal call carries two distinct identities:

  • The subject: the user on whose behalf the work is done. This is usually the sub claim plus whatever scopes or roles were granted at login.
  • The calling workload: the service making the request right now. This is its service identity, which is established independently of any user.

Authorization usually needs both. "May user 4812 see order 9931?" is a question about the subject. "May the billing service request order data on a user's behalf at all?" is a question about the caller. A compromised or buggy internal service holding a valid user token should not be able to reach endpoints it was never meant to call.

A single token rarely captures both identities well. A user's JWT says nothing reliable about which service is presenting it, because it is a bearer credential and anyone holding it can replay it. A service credential, on its own, carries no user context.

This matters most to backend and platform engineers running more than a couple of services behind a gateway. That is the point where "the gateway checked it" stops being a sufficient security model.

Why is forwarding the edge JWT unchanged risky?

The default in most systems is pass-through: the gateway validates the incoming JWT, then every service copies the Authorization header onto its outbound calls. It needs no new infrastructure, and each downstream service sees the original user's claims. The cost is that every service in the chain now holds a bearer credential. Anyone who presents it is treated as the user, so a token sitting in one service's memory, logs, or crash dumps is usable everywhere it is accepted.

The main defense against that replay is the audience claim. aud states which recipients the token is meant for. A service that rejects tokens not addressed to it cannot be called with a token stolen from a neighbor. Pass-through undermines this in one of two ways:

  • The token's audience is set broadly, such as a single value shared by the whole API surface, because one token has to be accepted at every hop.
  • Services skip the aud check, since many JWT libraries only enforce it when you configure an expected value.

In both cases, a compromised or buggy service can replay the token against every service that accepts that audience. That includes services it would never call in normal operation. The blast radius is the token's full scope, not the narrow permission the calling service actually needed.

Pass-through is still acceptable when a small, trusted set of services sits inside a single trust boundary, is operated by one team, and enforces strict audience checks. Beyond that, the shared token becomes a shared liability.

What are the alternatives: pass-through, gateway-minted tokens, or token exchange?

…becomes a liability, and two other patterns are worth comparing.

Pass-through:     client --[aud=api]--> gateway --[aud=api]--> A --[aud=api]--> B
Gateway-minted:   client --[aud=api]--> gateway --[aud=A, iss=internal]--> A --[aud=A]--> B
Token exchange:   client --[aud=api]--> gateway --[aud=A]--> A ==STS==> --[aud=B]--> B

In the gateway-minted case, A forwards the token it received, so B sees aud=A. B must either accept that audience or the gateway has to mint a token whose audience covers the whole internal mesh. In practice the audience usually widens. With token exchange, A presents its inbound token to the security token service (STS) and receives a new token narrowed to B before it calls B.

Pattern Fits when Avoid when Main cost
Pass-through Few services, one team, one trust boundary Many teams or any third-party code in the path A leaked token works at every hop
Gateway-minted You want services independent of the external IdP's claims and key rotation You cannot protect and rotate an internal signing key properly A second high-value key, and claim mappings that drift
Token exchange (RFC 8693) Least privilege per hop matters, as in regulated data or deep call chains Latency budgets are tight, or the STS cannot be run highly available An extra round trip per hop, and the STS becomes a critical dependency

Gateway minting hides IdP details from internal services. The cost is that the gateway's signing key can now mint any identity, and every claim rename at the IdP needs a matching change to the mapping. Token exchange gives the narrowest tokens, but it pushes teams toward caching exchanged tokens. A cached token outlives a revocation of its parent until it expires. If the cache key leaves out the requested scope or audience, a service can also reuse a token that is broader than the current call needs.

(1) Pass-through: original user JWT forwarded unchanged
+--------+           +---------+           +-----+           +-----+
| client | aud=api   | gateway | aud=api   |  A  | aud=api   |  B  |
|        |---------->|         |---------->|     |---------->|     |
+--------+           +---------+           +-----+           +-----+

(2) Gateway-minted: internal issuer, reduced claim set
+--------+           +---------+ aud=A     +-----+           +-----+
| client | aud=api   | gateway | iss=int   |  A  | aud=A     |  B  |
|        |---------->|         |---------->|     |---------->|     |
+--------+           +----+----+           +-----+           +-----+
                          |                       A forwards: B must accept
                  +-------+--------+              aud=A, or aud widens
                  | internal key   |
                  +----------------+

(3) Token exchange (RFC 8693): narrowed token minted per hop
+--------+           +---------+           +-----+           +-----+
| client | aud=api   | gateway | aud=A     |  A  | aud=B     |  B  |
|        |---------->|         |---------->|     |---------->|     |
+--------+           +---------+           +-+-+-+           +-----+
                                             | ^
                               inbound token | | exchanged, aud=B
                                             v |
                                         +---+-+----+
                                         |   STS    |
                                         +----------+

A request flowing gateway to service A to service B under pass-through, gateway-minted, and per-hop token exchange, with the token audience shown on each hop.

How does OAuth 2.0 token exchange work hop by hop?

Each hop that needs to call another service sends a token request to the authorization server instead of forwarding what it received. The subject_token is the incoming user token and identifies whose authority is being used. The actor_token is the calling service's own credential and identifies who is acting. The request carries these form parameters:

  • grant_type=urn:ietf:params:oauth:grant-type:token-exchange
  • subject_token with subject_token_type=urn:ietf:params:oauth:token-type:access_token
  • actor_token with actor_token_type=urn:ietf:params:oauth:token-type:jwt
  • audience=billing-service and scope=invoices:read

The authorization server checks that the actor is allowed to act for this subject toward that audience, then issues a new token. In the decoded payload, sub is still the user, aud is billing-service, and scope is invoices:read. An act object carries the actor's sub, for example orders-service. Billing can then enforce "user 4821, via orders" rather than only "user 4821."

Every further hop nests the previous act inside the new one. RFC 8693 treats only the outermost actor as relevant for access decisions and the nested ones as informational. Each hop still makes the token larger, and policy authors struggle to write rules about arbitrary chains. Many teams therefore cap chain depth or keep only the immediate actor.

Exchange is also where you trim claims. Drop group memberships, email, and unrelated scopes that the target does not use. The cost shows up later, when a downstream team needs a claim that was removed. Getting it back means changing the exchange policy, which the platform team owns, so every new claim requires coordination across teams.

# orders-service exchanges the incoming user token before calling billing-service.
# TOKEN_ENDPOINT, USER_TOKEN and ORDERS_SVC_JWT are placeholders set elsewhere.
curl -s -X POST "$TOKEN_ENDPOINT" \
  --data-urlencode 'grant_type=urn:ietf:params:oauth:grant-type:token-exchange' \
  --data-urlencode "subject_token=$USER_TOKEN" \
  --data-urlencode 'subject_token_type=urn:ietf:params:oauth:token-type:access_token' \
  --data-urlencode "actor_token=$ORDERS_SVC_JWT" \
  --data-urlencode 'actor_token_type=urn:ietf:params:oauth:token-type:jwt' \
  --data-urlencode 'audience=billing-service' \
  --data-urlencode 'scope=invoices:read'

# Decoded payload of the issued token (illustrative):
# {
#   "iss": "",
#   "sub": "user-4821",            <- still the original user
#   "aud": "billing-service",      <- narrowed to the next hop only
#   "scope": "invoices:read",      <- trimmed; no groups, email or unrelated scopes
#   "exp": 1767225600,
#   "act": {
#     "sub": "orders-service",     <- current actor: the one used for access decisions
#     "act": {
#       "sub": "api-gateway"       <- earlier hop: informational only per RFC 8693
#     }
#   }
# }
# Capping chain depth would drop the inner "act" and keep only orders-service.

An RFC 8693 token-exchange request sent by orders-service and the decoded result, showing the user kept in sub, the narrowed aud and scope, and a nested act chain whose outermost entry is the immediate caller.

How should services establish service identity separately from user identity?

A user token says who the request is for. It says nothing about which workload actually sent it, so the receiving service needs a second, independent proof of the caller.

There are two common ways to get it:

  • Mutual TLS with workload certificates. Each service holds a short-lived certificate whose identity (for example, a SPIFFE ID in the URI SAN) names the workload. The receiver reads the peer identity from the handshake. Identity is bound to the connection, and credentials rotate without application changes.
  • Client-credentials tokens. The calling service authenticates to the authorization server as itself and presents that token, or the server records it in the act claim of an exchanged token. This works across network boundaries where end-to-end mTLS isn't possible.

The receiver then checks both identities together. The simplest rule is a per-audience allowlist. For audience orders-api, accept user tokens only when the caller is checkout or support-console, and require the orders:read scope. When tokens carry act, also require that act.sub equals the mTLS peer identity. That match stops a leaked exchanged token from being replayed by a different workload, because the token is only valid on a connection from the service it was issued to.

A mesh can take certificate handling out of application code entirely, which is a real benefit. It also creates a blind spot. Teams see "mTLS: enforced" and assume authorization is handled. The mesh proves that checkout called orders. It does not prove that this user may read this order. That decision still belongs in the service, which has to evaluate the user token's claims against the resource being accessed.

# Per-audience caller allowlist, checked alongside the user token.
CALLER_POLICY = {
    "orders-api": {
        "allowed_callers": {
            "spiffe://example.internal/ns/shop/sa/checkout",
            "spiffe://example.internal/ns/support/sa/support-console",
        },
        "required_scopes": {"orders:read"},
    },
}

def authorize_caller(claims: dict, peer_id: str, audience: str = "orders-api") -> None:
    """claims: user token whose signature, expiry and issuer are already verified.
    peer_id: workload identity read from the verified mTLS peer certificate."""
    policy = CALLER_POLICY[audience]

    aud = claims.get("aud")
    if audience not in (aud if isinstance(aud, list) else [aud]):
        raise PermissionError("token was not issued for this audience")

    # Service identity: only listed workloads may present user tokens here.
    if peer_id not in policy["allowed_callers"]:
        raise PermissionError(f"{peer_id} may not present tokens for {audience}")

    scopes = set(claims.get("scope", "").split())
    if not policy["required_scopes"] <= scopes:
        raise PermissionError("missing required scope")

    # Exchanged tokens name the acting service in 'act'. Assumes the authorization
    # server issues act.sub in the same form as the mTLS identity (a SPIFFE ID).
    # A mismatch means the token is being replayed from a different workload.
    act = claims.get("act")
    if act is not None and act.get("sub") != peer_id:
        raise PermissionError("act.sub does not match mTLS peer identity")

    # Passing only proves an allowed workload is acting for this user.
    # Whether claims["sub"] may read the specific order is a separate,
    # per-resource check inside the handler.

A receiving service checks the mTLS peer identity against a per-audience allowlist, requires a scope, and matches act.sub to the peer, while leaving per-resource user authorization to the handler.

How do you implement JWT validation and propagation in each service?

Every service validates the token itself, even behind a gateway. A request that arrives through an internal route, a debug port or a misconfigured mesh never passed the gateway's checks. The inbound middleware runs these steps in order:

  1. Extract the bearer token. Reject it if it is missing or malformed.
  2. Read alg and kid from the header. Reject any algorithm not on the allowlist before looking up a key.
  3. Find kid in the cached JWKS. On a miss, refresh once, rate-limited so attackers cannot force fetches, then reject if it is still unknown. Rotation works because issuers publish the new key before signing with it and keep the old key until tokens signed with it have expired.
  4. Verify the signature, then check iss, aud, exp and nbf with a small skew allowance. Attach the subject, scopes and calling service identity to the request context.

The outbound client never copies the inbound Authorization header. It asks a token provider for a token whose audience is the target service. The provider returns a cached exchanged token or performs a new exchange.

Rule Failure prevented
Algorithm allowlist none tokens, key-confusion attacks
Signature via JWKS Forged tokens
iss match Tokens from another issuer
aud match Replaying a token meant for a different service
exp/nbf with bounded skew Reuse of expired tokens

Teams with services in several languages often reimplement this logic for each one. A shared library per language saves that effort. The risk is a service pinned to an old copy that predates the audience or allowlist checks. That service skips those checks without any error, so track library versions in CI.

ALLOWED_ALGS = {"RS256", "ES256"}        // explicit allowlist; "none" and HS* never match
EXPECTED_ISS = ""
SELF_AUD     = "orders-service"
SKEW         = 60 seconds                  // bounded clock-skew allowance

function inbound_middleware(request, next):
  token = parse_bearer(request.header("Authorization")) or reject(401)
  header = decode_header_unverified(token)   // only alg and kid are read here
  if header.alg not in ALLOWED_ALGS: reject(401)   // checked before any key lookup
  key = jwks_cache.get(header.kid)
  if key is null and jwks_cache.may_refresh():     // rate-limited refresh on unknown kid
    jwks_cache.refresh()
    key = jwks_cache.get(header.kid)
  if key is null: reject(401)
  if key.alg is set and key.alg != header.alg: reject(401)  // block key confusion
  claims = verify_signature(token, key, header.alg) or reject(401)
  now = clock()
  if claims.iss != EXPECTED_ISS: reject(401)
  if SELF_AUD not in as_list(claims.aud): reject(401)  // token must be meant for us
  if claims.exp is missing or now > claims.exp + SKEW: reject(401)
  if claims.nbf is set and now + SKEW < claims.nbf: reject(401)
  request.context.identity = {subject: claims.sub, scopes: claims.scope,
                              caller: claims.client_id, raw_token: token}
  return next(request)

function call_downstream(ctx, target_aud, outbound_request):
  // never forward the inbound Authorization header as-is
  token = token_provider.get(ctx.identity.raw_token, target_aud)
  outbound_request.header("Authorization") = "Bearer " + token
  return http_send(outbound_request)

function token_provider.get(subject_token, audience):
  cache_key = (sha256(subject_token), audience)
  cached = token_cache.get(cache_key)
  if cached and cached.exp > clock() + 30 seconds: return cached.token
  result = token_exchange(subject_token, audience)  // e.g. OAuth 2.0 Token Exchange (RFC 8693)
  token_cache.put(cache_key, result, expires_at = result.exp)
  return result.token

Language-neutral pseudocode for an inbound middleware that enforces the algorithm allowlist, JWKS lookup with rate-limited refresh, and iss/aud/exp/nbf checks, paired with an outbound client that obtains an audience-specific token via a cached exchange instead of forwarding the caller's header.

How do you handle async jobs, token lifetimes, and audit logging?

Queues and background jobs

A user JWT placed in a queue message has a lifetime that started at login, not at enqueue. If the token expires in five minutes and the consumer runs after a backlog or a retry, validation fails and the job dies for reasons unrelated to the user's permissions. Instead, validate the token at enqueue time. Write the verified subject, tenant, and relevant scopes into the message as plain fields. The consumer then authenticates to downstream services with its own service identity and treats the user fields as data that the producer already checked. Only trusted producers can write to the queue, so the queue's access control now also protects these user fields.

Lifetime trade-offs

Short lifetimes shrink the window for replaying a stolen token, but they break deep or slow call chains partway through. Long lifetimes keep chains working but extend the replay window. A JWT cannot be revoked by itself. Revocation needs extra state, such as a jti denylist or an introspection call, and that brings back the per-request lookup that self-contained tokens were meant to avoid.

Audit logging

At each hop, log the subject, the chain of acting services, and the jti. Never log the full bearer token. Attach the trace ID so you can reconstruct a single request across all services.

Choosing a pattern

Small teams inside one trust boundary can start with gateway-minted internal tokens. Once services cross team, tenant, or network boundaries, adopt token exchange. Do this before an incident, because building consistent audit logs and service identity afterward is much harder.

How OneEnv can help

Disclosure: OneEnv is the product behind this blog.

OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.

Applied to jwt propagation microservices, this is where it helps:

Saves time

  • Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
  • One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
  • Changing a route's URL or method automatically notifies the services that consume it — no hunting through repos for callers.

Saves cost

  • Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
  • Less duplicated configuration to maintain: one shared definition inherited by many services.
  • Consumers learn about a breaking change at review time rather than from production errors.
  • OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.

These are qualitative benefits, not measured results — how much you save depends on how many services share the value.

Want to try it? Start at oneenv.io.