Skip to main content
Many APIs receive a JSON Web Token (JWT) from the client, often as a bearer token or in a custom header, and are expected to tailor their response based on the claims it contains. This guide shows how to extract a JWT from an incoming request and use its claims when building a templated stub response.
This is the reverse of generating a JWT - here we’re reading claims out of a token the client sent us, not signing a new one.

The problem

A JWT is made up of three base64url-encoded segments separated by . - a header, a payload and a signature. The claims you want to use in your response live in the payload segment, so to get at them you need to:
  1. Read the token out of the request
  2. Split it into its three segments and take the payload (the second one)
  3. Base64-decode the payload
  4. Parse the decoded string as JSON so its claims can be referenced

Example

Suppose an incoming request carries its JWT in an X-JWT-Assertion header, and you want to echo the token’s sub and a custom apiName claim back in the response body. Enable templating on the stub’s response and use the following as the body:

How it works

  • request.headers.[X-JWT-Assertion].[0] reads the first value of the X-JWT-Assertion header. The square-bracket form is used because the header name contains a hyphen.
  • split divides the token string on ., giving you the three JWT segments as a list.
  • lookup retrieves a value by key, using the same square-bracket convention as request.headers.[key] above to treat the bracketed content as a single literal key rather than a dotted property path. This is what lets you pull out the segment at array index 1 (the payload), and later the my.org/claims/apiname claim, even though both contain characters (/, digits-only) that wouldn’t work with plain dot notation.
  • base64 with decode=true decodes the payload segment back into its raw JSON string.
  • parseJson turns that JSON string into an object so its claims can be accessed directly.
  • Claims with names that are valid identifiers, like sub, can be read with plain dot notation (jwtClaims.sub).
  • val is used throughout to assign each intermediate result to a variable, and trim strips the surrounding whitespace left by the val lines from the final output.
This only decodes the JWT’s payload - it does not verify the token’s signature. Don’t rely on this technique alone to authenticate a request; treat the claims as untrusted input for the purposes of your mock.
If you need to reject requests that don’t carry a valid-looking token, combine this with a header matcher on the header before falling through to a default response - see serving a default response.