JWT, JWS, JWE, and JOSE in Depth
Back to Learn
FAACChapter 18

Corporate API Fundamentals and Architecture

JWT, JWS, JWE, and JOSE in Depth

From claims structure to signatures, encryption, key distribution, rotation, and secure validation in API Gateways

In-depth edition - study material and professional reference

Layered token protected by signatures, encryption, and key governance in an API architecture

Cryptography, Context, and Governance for Secure Tokens

Cryptographic cycle of a token between issuer, JWS or JWT, API Gateway and backend
Opening Figure - Secure tokens depend on encryption, context, recipient, and key governance.

Central principle

Signature protects integrity and origin; encryption protects reading. None of them replace issuer, audience and purpose validation.

In-depth edition - study material and professional reference

Chapter presentation

The previous chapter presented OpenID Connect and showed that ID Tokens, access tokens, logout tokens and other artifacts can use JSON Web Token as a format. However, recognizing three segments separated by dots is not enough to trade tokens safely. It is necessary to understand the JOSE family, the difference between claims and cryptographic protection, the selection of algorithms, the distribution of keys and the specific validations for each profile.

is a framework for transporting claims. protects content with a digital signature or message authentication code. protects confidentiality by authenticated encryption. represents a key in JSON; a publishes key sets; records algorithms and identifiers. These components combine, but are not synonymous. A can be a , a , or a nested structure.

In enterprise APIs, the most serious errors are rarely in decoding. They arise when the consumer accepts unforeseen algorithms, chooses keys using untrusted data, ignores issuer or audience, mixes ID Token and access token, reuses the same rule for different types of or maintains key rotation incompatible with caches and token lifetime.

This chapter delves into compact and JSON serializations, protected headers, claims, , , thumbprints, rotation, , nested tokens, and access token profiles. It also incorporates best practices from RFC 8725 and the update to RFC 9864 on fully specified algorithm identifiers, as well as relating the concepts to Axway API Gateway, Azure API Management, and validation libraries.

How to study this chapter

For each example, answer in order: what is the type of the object, who issued it, who is the recipient, which algorithm is allowed, where the key comes from, which bytes were protected and which claims need to be validated. This sequence reduces the chance of accepting a token just because its signature appears valid.

Learning Objectives

  • Distinguish JOSE, , , , , and .
  • Explain , UTF-8, JSON and the impact of exact byte representation.
  • Interpret registered, public and private claims without confusing presence with trust.
  • Describe Compact Serialization and JSON Serialization.
  • Differentiate digital signature and MAC, including non-repudiation and key distribution implications.
  • Restrict algorithms by allowlist and avoid algorithm confusion.
  • Use , , and in a safe and contextual way.
  • Interpret RSA, EC, OKP and oct and separate public material from private material.
  • Plan , caching, rotation, rollover and key removal.
  • Explain the and parameters in and the five-part structure.
  • Design nested tokens and decide when to sign, encrypt, or use both.
  • Validate JWTs cryptographically, temporally and semantically.
  • Apply profile to access tokens and distinguish other types.
  • Diagnose signature, audience, issuer, , cache, clock and encryption failures.

Chapter structure

  • 18.1 The JOSE family and its responsibilities
  • 18.2 , UTF-8 and canonical JSON
  • 18.3 : claims and security envelope
  • 18.4 Registered claims, public and private
  • 18.5 : signing input and serializations
  • 18.6 Digital signature and MAC
  • 18.7 Algorithms, allowlists and RFC 9864
  • 18.8 Headers , , and
  • 18.9 : anatomy and key types
  • 18.10 and key distribution
  • 18.11 , thumbprints and X.509 certificates
  • 18.12 Key rotation, caching, and key retirement
  • 18.13 : , and Content Encryption Key
  • 18.14 Serializations and Multiple Recipients
  • 18.15 and order of protections
  • 18.16 Secure Validation Pipeline
  • 18.17 Profile for OAuth 2.0 access tokens
  • 18.18 Other profiles
  • 18.19 Proof-of-possession and claim cnf
  • 18.20 Application in API Gateways, Axway, and Azure
  • 18.21 Threats and hardening
  • 18.22 Privacy, logging and minimization
  • 18.23 Troubleshooting
  • 18.24 Case studies and labs
  • Summary, checklist, exercises, glossary and references
JOSE family separating JWT, JWS, JWE, JWK, JWKS and JWA due to liability
Figure 1 - JOSE is a family of structures; is just one part of the model.

18.1 The JOSE family and its responsibilities

JSON Object Signing and Encryption is the set of specifications that define JSON structures for signing, authentication, encryption, and key representation. The objective is to transport security objects in a way that is compatible with HTTP, URIs and applications that already use JSON. The family was divided into documents to separate structure, algorithms, keys and claims semantics.

defines a set of claims and processing rules. defines how to protect a sequence of bytes with a digital signature or MAC. defines authenticated encryption and content key management. defines how to represent cryptographic keys in JSON, while associates identifiers such as RS256, ES256 or A256GCM with concrete operations.

A token commercially called a is usually a in compact serialization, but this is a frequent convention, not a formal equivalence. There are also encrypted JWTs like , JWSs whose payload is not a , and JOSE objects with multiple signatures or recipients using JSON serialization.

Table 1 - Each JOSE component solves a different responsibility.
StructureProtection or functionUsage example
JWTSet of claims with semantics defined by a profile.ID Token, access token, client assertion or logout token.
JWSIntegrity and authentication by signature or MAC.Signed token and signed webhook.
JWEConfidentiality and integrity through authenticated encryption.Token with sensitive claims intended for a specific recipient.
JWK/JWKSRepresentation and publication of keys.Issuer public keys for validation.
JWAAlgorithm and parameter identifiers.RS256, ES256, A256GCM and RSA-OAEP-256.

18.2 , UTF-8 and JSON representation

transforms bytes into URL-safe characters by replacing the + and / characters and typically removing the = padding. The operation does not encrypt, does not compress and does not provide integrity. Anyone who receives a compact can decode header and payload, even if they do not have the signing key.

Before encoding, JSON objects are converted to UTF-8 bytes. Spaces, member order, escapes, and numeric forms can produce different byte sequences even when two representations appear semantically equivalent. In , the signature covers the exact representation used in the signing input; a library should not decode the payload and reserialize it to verify the signature.

JSON allows flexibility that requires defensive validation. Duplicate member names, numbers outside the expected range, strings with different normalization, and multiple representations can cause differing interpretations between libraries. The profile that uses must define accepted claims, types and limits, rejecting ambiguous objects.

Exemplo conceitual - transformação do header
header JSON: {"alg":"RS256","typ":"JWT","kid":"key-2026-07"}
BASE64URL(UTF8(header))
  eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6ImtleS0yMDI2LTA3In0
Base64url e apenas codificacao. O conteudo permanece legivel.

Recurring error

Hiding a token in the browser, in a header or in a log is not equivalent to protecting confidentiality. A signed remains readable. To prevent content from being read, or other suitable channel and storage protection is required.

18.3 : claims and security envelope

A claim is an assertion represented by a name-value pair. The is a JSON object that brings together these claims. The format does not automatically determine who can issue the claim, how long it is valid or how it should be interpreted. These rules pertain to the profile and the trust relationship between sender and recipient.

can be protected by or . In a , claims are readable, but changes are detectable when the signature is verified correctly. In a , the content is encrypted and authenticated. In both cases, the recipient still needs to validate issuer, audience, time, type and application-specific rules.

Claims should not carry arbitrary state just because the token supports JSON. Large tokens increase bandwidth usage, header size, pressure on proxies and risk of exposure. The issuance must prioritize stable data necessary for the decision, using identifiers for information that needs to be consulted in real time.

Table 2 - Registered claims have general semantics, but the profile defines the concrete obligation.
ClaimGeneral semanticsTypical validation
issIssuer identifier.Accurate comparison with issuer enabled.
subIdentifier of the subject in the sender.Interpret together with this and the profile.
audRecipient or set of recipients.Contain the audience of the API or client.
expInstant after which the token should not be accepted.Synchronized clock and small tolerance.
nbfInstant before which the token should not be accepted.Reject early use outside of tolerance.
iatEmission time.Check plausibility and age policies.
jtiUnique token identifier.Replay detection or audit when the profile requires it.

18.4 Registered claims, public and private

Registered claims have names and semantics documented in the IANA registry, such as iss, sub, aud, exp and jti. They are not mandatory in every , but profiles such as OIDC and RFC 9068 specify which ones should appear. Correct usage depends on respecting the intended JSON type and the purpose of the profile.

Public claims use collision-resistant names, typically registered or based on a URI controlled by the organization. Private claims are local agreements between issuer and consumer, such as roles, tenant_id, or transaction_limit. They are useful, but they can clash across ecosystems and change meaning when a token crosses organizational boundaries.

An authorization claim should not be accepted just because it exists. The resource server needs to know the issuer, profile, namespace, type and policy that produces it. For example, roles issued by a directory may represent administrative groups rather than domain permissions. The application must transform reliable claims into explicit local decisions.

Claim design

Prefer stable names, simple types, and documented meaning. Avoid including secrets, unnecessary personal data, huge lists of groups, or business objects that change during the token's validity.

JWS Compact Serialization with protected header, payload, signature and signing input
Figure 2 - The signature covers the protected header and the encoded payload, joined by a dot.

18.5 : signing input and serializations

Compact Serialization has three parts: protected header, payload and signature. The first two are encoded in and joined by a dot to form the signing input. The algorithm uses this value and the appropriate key to produce the third part. The check reconstructs the same bytes and validates the cryptographic operation.

JSON Serialization represents the object as JSON and allows multiple signatures on the same payload. The flattened form contains a signature; the general form contains a collection. This model is useful when different organizations or keys need to sign the same content, although it increases policy and processing complexity.

RFC 7797 allows non- -encoded payloads through the b64 parameter in the protected header and the use of . This option is specialized and can improve integration with highlighted content, but requires explicit support and care for characters that interfere with compact serialization. Common APIs should prefer the default behavior offered by mature libraries.

Pseudocódigo - construção conceitual de um JWS
protected = BASE64URL(UTF8({"alg":"ES256","kid":"ec-1"}))
payload   = BASE64URL(payload_bytes)
signing_input = protected + "." + payload
signature = ECDSA_sign(private_key, signing_input)
jws_compact = protected + "." + payload + "." + BASE64URL(signature)

18.6 Digital signature and MAC

Asymmetric algorithms use private key to sign and public key to verify. The issuer keeps the private key under control and distributes only public material. This model facilitates validation by multiple APIs and reduces the ability of validators to issue tokens, as having the public key does not allow creating new signatures.

MAC algorithms such as HMAC use the same secret to produce and verify code. Every component capable of validating can also generate an indistinguishable token. In architectures with many resource servers, secret sharing increases the impact of compromise and makes it difficult to assign which component produced a token.

Digital signature does not automatically create legal non-repudiation. Logs, key control, certification, policy, auditing, and context are required. Likewise, verifying the signature only proves that the bytes correspond to an accepted key; it does not prove that the token is current, intended for that API, or authorized for the operation.

Table 3 - The choice of model changes boundaries of trust and incident response.
ModelDistributionOperational implication
Asymmetric signaturePrivate at the issuer; public on validators.Validators are unable to issue tokens. Facilitates JWKS and rotation.
Symmetrical MACSame secrecy at issuer and validators.Any committed validator can craft tokens.
Signature with HSM/KMSPrivate operation in controlled module.Reduces key exposure and improves auditing, with cost and dependency.

18.7 Algorithms, allowlists and RFC 9864

The header declares the algorithm used, but should not alone control the decision. The consumer must have an allowlist configured by profile, issuer and token type. If the application accepts any advertised algorithm, algorithm confusion, downgrade or use of an incompatible operating key may occur.

Algorithms need to be evaluated for the full set of parameters, key size, library, regulatory requirements, and interoperability. RS256 remains widely supported; PS256 uses RSA-PSS; ES256 uses ECDSA with P-256 and SHA-256. Modern algorithms based on EdDSA must consider updates to fully specified identifiers and actual ecosystem support.

RFC 9864, published in 2025, differentiates fully specified algorithms from those that rely on external parameters to determine operation. It updates JOSE records and deprecates polymorphic identifiers in situations covered by the specification. New architectures should consult the current IANA registry and avoid negotiating ambiguous names just for historical compatibility.

Table 4 - The algorithm should be chosen by policy, not by the untrusted content of the token.
AlgorithmFamilyAttention
RS256RSA PKCS#1 v1.5 with SHA-256Broad support; use sufficient wrench and governed rotation.
PS256RSA-PSS with SHA-256Probabilistic padding; confirm support of all components.
ES256ECDSA P-256 with SHA-256Compact signature; requires correct implementation of ECDSA.
HS256HMAC with SHA-256Shared secret turns validators into potential issuers.
noneNo cryptographic protectionDo not accept in security tokens.
EdDSA / updated namesEdwards curvesConsult RFC 9864 and IANA registry for identifier and current support.

Security rule

Configure expected algorithm next to the issuer and the token type. Do not derive the allowlist from the header itself, and do not reuse the same key in incompatible algorithm families.

18.8 Headers , , and

The type parameter declares the type of object for the application. It doesn't change the encryption, but it helps prevent confusion between JWTs with different purposes. RFC 8725 recommends explicit typing and mutually exclusive rules. The RFC 9068 access token profile uses at+ , while ID Tokens often use or rely on the OIDC context.

describes the payload type, being especially useful in nested objects. A that contains a signed can use equal to . is a tip for selecting a key among several; is not a global identifier, does not prove ownership and can be repeated between issuers.

lists header parameters that need to be understood to process the object. If a critical item is unknown, the consumer must reject the token. Ignoring destroys the ability of extensions to modify security semantics. Headers that influence the cryptographic operation must be in the protected area, not just in unprotected fields of JSON serialization.

Table 5 - Headers guide processing, but require local policy.
HeaderFunctionValidation
typObject type for the application.Compare with the expected profile and separate rules.
ctyType of protected content.Use in nesting and non-obvious content.
kidSelect candidate key.Resolve only within the trusted issuer.
critExtensions that need to be understood.Reject if any item is not supported.
jku/x5uURL of keys or certificates.Do not fetch freely from untrusted token.

18.9 : anatomy and key types

JSON Web Key represents cryptographic material with parameters defined by kty. A public RSA key includes n and e; an EC key includes crv, x and y; an OKP key includes curve and public coordinate; a symmetric key oct includes k. Private parameters such as d, p, q, or k should not appear in public .

use indicates broad purpose, such as sig or . key_ops lists specific operations, such as verify, sign, encrypt, or decrypt. can restrict association with an algorithm. These fields need to be coherent with each other and with the application policy; they should not automatically expand what the key can do.

Keys must have origin, owner, activation date, withdrawal date, purpose and revocation procedure. Representing a key in JSON does not eliminate secret controls. Private keys must remain in HSM, KMS, vault, or secure storage and be loaded only by authorized processes.

Exemplo - JWK pública RSA
{
  "kty": "RSA",
  "kid": "signing-2026-07",
  "use": "sig",
  "alg": "RS256",
  "n": "sXch...base64url-modulus...",
  "e": "AQAB"
}

Private material

A public must contain only public parameters. The presence of d, p, q, dp, dq, qi, or k may expose a private key or symmetric secret and requires immediate incident response.

18.10 and key distribution

A JSON Web Key Set contains the keys property with a list of . Identity providers publish for clients and resource servers to verify signatures. The endpoint must be obtained by trusted configuration or metadata linked to the issuer, never by an arbitrary URL provided by the token.

The consumer maintains cache to avoid network dependency on each request. The cache must respect HTTP policies, have a size limit, timeout, controlled update and safe fallback. In the event of temporary endpoint failure, known keys may continue to be valid according to policy, but keyless tokens should not be accepted just to preserve availability.

Validation must first fix the allowed issuer, find the corresponding set, and then use , kty, and key_ops to filter candidates. A global cache indexed only by allows for collisions between tenants and issuers. The secure index includes at least the issuer and key identifier.

Table 6 - Key distribution is part of token availability and security.
ComponentResponsibilityTypical failure
Issuer configurationSet trusted domain and profile.Token from another tenant or accepted environment.
jwks_uriPublish current public keys.URL changed or unavailable.
CacheReduce latency and dependency per request.New unseeded key or old eternal key.
Selection by kidChoose candidate from the trusted set.Global collision or non-existent kid.
UpdateSearch set when necessary.Refresh storm induced by malicious tokens.

18.11 , thumbprints and X.509 certificates

is an identifier chosen by the issuer and can be an opaque string. It facilitates rotation, but does not have global uniqueness. , defined by RFC 7638, computes a digest over a canonical representation of the key's required members and produces identifier derived from the public material itself.

x5c can carry an X.509 certificate chain; x5t and x5t#S256 carry certificate thumbprints. When certificates are used, the consumer needs to validate chain, key usage, validity and trust according to the profile. Comparing just a received in the token does not create a reliable anchor.

jku and x5u point to remote resources. Following these URLs without allowlist creates SSRF, access to internal networks and key rollover. On enterprise platforms, metadata endpoints and must be pre-configured, resolved through controlled and monitored channels.

Pseudocódigo - JWK Thumbprint
thumbprint_input = canonical_json({
  "e": "AQAB",
  "kty": "RSA",
  "n": "sXch..."
})
jwk_thumbprint = BASE64URL(SHA256(UTF8(thumbprint_input)))
Key rotation with early publishing, overlay, and secure retirement
Figure 3 - Secure rotation publishes the new key before using it and keeps the old one during rollover.

18.12 Key rotation, caching, and key retirement

Planned rotation begins with early publication of the new key. After caches have had the opportunity to update it, the issuer starts signing new tokens with the new . The previous key remains published until all tokens signed by it have expired, plus clock tolerances, queues, retries and propagation delay.

Removing the key immediately after changing the signer causes tokens that are still valid to fail. Keeping keys indefinitely reduces revocation capacity and expands surface area. The window must be calculated based on maximum token lifetime, refresh, cache-control, update times and behavior of disconnected components.

When an unknown appears, the validator can update the once within limits and use coalescence to avoid multiple simultaneous searches. Random tokens should not trigger a request per attempt. Rate limiting, short negative cache and circuit breaker protect the metadata endpoint and the gateway itself.

In key compromise, priority may require immediate withdrawal and invalidation of tokens, accepting controlled unavailability. The plan needs to define detection, emergency rotation, communication to consumers, revocation, analysis of improper issuance and restoration of trust.

Operating equation

Minimum overlap time must consider: maximum token life + clock tolerance + cache delay + queues and retries. Use real metrics, not just nominal exp value.

JWE Compact Serialization with protected header, encrypted key, IV, ciphertext and tag
Figure 4 - separates key management and authenticated content encryption.

18.13 : , and Content Encryption Key

uses a Content Encryption Key, or , to encrypt plaintext with the authenticated encryption algorithm denoted by . The parameter defines how this is secured, transported, derived, or shared with the recipient. Therefore, and have different responsibilities and both must be allowed by the policy.

In RSA-OAEP-256, the is encrypted with the recipient's RSA public key. In dir, the shared symmetric key is directly used as . In ECDH-ES, a key agreement operation derives material from elliptical keys. The choice changes key distribution, forward secrecy, interoperability and risk of compromise.

Algorithms like A256GCM provide confidentiality and integrity in a single authenticated operation. IV or nonce must comply with the algorithm requirements and cannot be reused under the same key when this compromises security. The authentication tag must be validated before releasing any plaintext to the application.

Encryption does not eliminate the need for a signature when the recipient needs to verify authorship separately. A proves that the tag is valid under the encryption key, but the identity of the producer depends on the key management mechanism and the profile. Nested tokens can combine signing and encryption.

Table 7 - JWE combines key management, content encryption and protected metadata.
ParameterExampleResponsibility
algRSA-OAEP-256Protect or establish the CEK for the recipient.
encA256GCMEncrypt content and produce authentication tag.
zipDEFCompress before encryption; use only with risk analysis.
kidrecipient-key-2Select decryption key within the trusted domain.
ctyJWTIndicate that the plaintext is a nested JWT.

18.14 Serializations and Multiple Recipients

Compact serialization has five parts: protected header, encrypted key, IV, ciphertext and authentication tag. It is suitable for a recipient and transport in parameters or headers. JSON serialization allows protected and unprotected fields, Additional Authenticated Data and multiple recipients, each with their own encrypted key.

Across multiple recipients, the same ciphertext can be shared while the is protected separately for each key. This reduces duplication, but creates more complex policy: all recipients receive the same content and need to be governed as a whole. Removing a recipient requires re-encryption for future messages.

Unprotected headers can be changed without invalidating the tag when they do not participate in . Information that determines algorithm, key, type or interpretation must be in the protected header. The consumer needs to know which fields are authenticated and reject inconsistent combinations.

Mapa da JWE Compact Serialization
protected.encrypted_key.iv.ciphertext.tag
1. protected: alg, enc, kid, cty
2. encrypted_key: CEK protected for the recipient
3. iv: unique value required by the algorithm
4. ciphertext: plaintext cifrado
5. tag: authenticity of ciphertext and associated data

18.15 and order of protections

A applies and in sequence. The common pattern is to sign first and encrypt later. The issuer creates a that preserves integrity and authorship, then uses that as the plaintext of a intended for the consumer. The outer uses the same as to indicate nested content.

After decryption, the recipient still needs to validate the internal . The validity of the external tag does not replace the internal token's signature, issuer, audience or time. Likewise, the internal signature does not prove that the external object was intended for the component that received it.

Encrypting and then signing exposes metadata and the external signature, and produces different semantics. Profiles must define the order, algorithms, types and error handling. Don't invent your own composition when a standardized profile or token-signed TLS channel meets the requirement.

Table 8 - The choice depends on confidentiality, autonomy, revocation and complexity.
StrategyPropertyUsage
JWS onlyIntegrity and origin; readable payload.Access common tokens over TLS channels.
JWE onlyConfidentiality and integrity under the encryption key.Content intended for specific recipient.
JWS within JWEInternal authorship and external confidentiality.Nested JWT with sensitive claims.
Opaque referenceServer queries state by identifier.Revocation and minimization when not necessary self-contained.
Secure JWT validation pipeline on a resource server
Figure 5 - Secure validation is a chain; skipping a step changes the trust model.

18.16 Secure Validation Pipeline

The validator starts with the external context: endpoint, expected issuer, token type and profile. It then does defensive parsing with limits on size, number of segments, JSON depth, and types. The untrusted header is only read to select an operation allowed within the configuration.

Key selection occurs in the set associated with the issuer. needs to be on the allowlist and compatible with kty, use and key_ops. The signature, MAC or tag is fully verified. Cryptographic failures terminate processing without trying alternative unauthorized algorithms.

After encryption come semantic validations: iss, aud, exp, nbf, iat, , , nonce, jti, scopes, tenant and profile claims. Rules for access token, ID Token, client assertion and logout token must be mutually exclusive. Accepting a token in multiple contexts favors cross- confusion.

Finally, authorization applies local rules. A valid token does not imply permission for any object. The backend must verify operation, resource, ownership, business context and current policies. Logs must record minimum results and identifiers, never the complete token.

Table 9 - Parsing, token authentication and authorization are different steps.
StepQuestionFailure result
ContextWhat type of token and issuer does this endpoint accept?Reject before trust in headers.
ParsingAre structure, size and JSON acceptable?Generic error without deep processing.
Algorithm and keyAllowed algorithm and correct issuer key?Reject; update JWKS only in a controlled manner.
CryptographyAre signature, MAC or tag valid?Reject without using claims.
ClaimsAre audience, time, type and profile rules valid?401 or corresponding protocol error.
AuthorizationCan the identity perform the action on the resource?403 or appropriate domain response.

18.17 Profile for OAuth 2.0 access tokens

RFC 9068 defines an interoperable profile for access tokens. It does not force OAuth to use ; access tokens can still be opaque. When the profile is adopted, the token must be signed, cannot use none and must declare equal to at+ , in addition to claims and specific rules for issuer, subject, audience, time, client_id and authorization.

The resource server validates the token for its own audience. Scopes may appear in scope, and additional authorization information may be carried depending on the profile and agreements. The token should not be accepted by APIs from another audience just because it was issued by the same Authorization Server.

access tokens reduce introspection calls and allow local validation, but make immediate revocation more difficult. Short lifetime, rotation, sender constraints, emergency lists, and session policies can reduce exposure. For data that needs to reflect instantaneous state, introspection or authorization query may be more appropriate.

Exemplo conceitual - header e claims de access token
{
  "typ": "at+jwt",
  "alg": "RS256",
  "kid": "as-signing-4"
}.
{
  "iss": "https://auth.example",
  "sub": "user-481",
  "aud": "https://api.example/payments",
  "client_id": "mobile-app",
  "scope": "payments.read payments.create",
  "iat": 1784126100,
  "exp": 1784126700,
  "jti": "8b28b730-..."
}

Access token is not ID token

The access token is intended for the resource server and describes authority. The ID Token is intended for the OIDC client and describes authentication. Even though both are JWTs signed by the same issuer, their rules cannot be interchanged.

18.18 Other profiles

is used in several profiles. ID Tokens follow OpenID Connect rules. RFC 7523 client assertions allow you to authenticate a client to the token endpoint or present a grant. RFC 9101 Request Objects protect authorization parameters. Logout tokens carry session-specific events. Introspection responses can be protected as as per RFC 9701.

Each profile defines type, audience, mandatory claims, time, replay and recipient. A generic library that only checks signatures does not know these rules. The application needs to select a specific validator or configuration for each type and maintain separate endpoints when possible.

New formats continue to emerge. RFC 9901, published in 2025, standardizes Selective Disclosure to allow selective presentation of claims in credential scenarios. This mechanism has its own issuance, presentation, disclosure and key binding model; it should not be treated as a traditional just because it reuses JOSE components.

Table 10 - Different types require mutually exclusive validation rules.
ProfileRecipientDistinctive control
OIDC ID TokenRelying Partyclient_id in aud, nonce and OIDC rules.
JWT access tokenResource Servertype at+jwt, API audience and RFC 9068 claims.
Client assertionAuthorizationServeraud from the endpoint, iss/sub from the client and replay by jti.
Logout tokenRelying Partyevents, sid/sub, jti and absence of nonce.
Request ObjectAuthorizationServerProtected authorization request parameters.
SD-JWTCredential VerifierSelected disclosures and key binding rules.

18.19 Proof-of-possession and claim cnf

Bearer tokens can be used by any party that obtains the value. Sender-constrained tokens bind usage to a key or certificate. The claim cnf confirms which key needs to be demonstrated. Binding can use key , certificate , or profile-defined parameters.

In DPoP, the client presents a proof per request and the access token can contain jkt, the of the public key. In mTLS-bound access tokens, cnf can contain x5t#S256 of the certificate used in the channel. The resource server verifies both the token and the corresponding proof or certificate.

Proof-of-possession reduces stolen token replay, but adds key management, synchronization, nonces, TLS proxies, and diagnostics. The gateway needs to preserve or verify the evidence at the correct point. Terminating mTLS in a component and forwarding only an untrusted header to the backend destroys the binding if that header can be injected externally.

Exemplos conceituais - confirmação da chave
"cnf": {
  "jkt": "0ZcOCORZNYzC-7hV..."
}
# ou, para certificado mTLS
"cnf": {
  "x5t#S256": "qP3Q...thumbprint..."
}

18.20 Application in API Gateways, Axway, and Azure

The API Gateway acts as a Policy Enforcement Point and needs to separate authorization token validation from the route. A robust policy fixes issuer, audience, algorithms, metadata location, mandatory claims and cache behavior. Headers derived from claims must replace external values and be sent to the backend only via a trusted channel.

In Axway API Gateway, validation filters and identity libraries can verify signatures, claims and certificates. The configuration must limit algorithms, choose store or per environment and correlate failures with safe traces. Shared policies avoid divergence, but need to allow for audience and profile differences between APIs.

In Azure API Management, validate- and validate-azure-ad-token integrate validation with OpenID configuration, audiences, and required-claims. The policy should verify the token intended for the API and not just accept any token from the tenant. Metadata caches and rotation need to be considered for changes and incidents.

When the gateway reissues internal token, a new trust relationship occurs. The external token must be validated first; the internal token must have its own issuer, audience, life and minimum claims. The backend trusts the internal issuer, not the original token, and the correlation must preserve identifiers for auditing.

Exemplo conceitual - política de validação no gateway
<validate-jwt header-name="Authorization"
              require-scheme="Bearer"
              failed-validation-httpcode="401">
  <openid-config url="https://auth.example/.well-known/openid-configuration" />
  <audiences>
    <audience>https://api.example/payments</audience>
  </audiences>
  <required-claims>
    <claim name="scope" match="all">
      <value>payments.read</value>
    </claim>
  </required-claims>
</validate-jwt>

Identity Propagation

Remove identity headers received from the Internet before creating internal headers. The backend should accept these values only from the authenticated gateway and, for critical decisions, continue to apply domain authorization.

18.21 Threats and hardening

Algorithm confusion occurs when the consumer allows someone to select an unforeseen operation, such as using an RSA public key as an HMAC secret. The defense is a fixed allowlist, separate keys by use and updated library. none should be rejected in security tokens, unless exceptional and explicitly isolated profile.

Substitution and cross- confusion occur when a valid token is accepted in the wrong context. ID Token used as an access token, token from another audience, staging token in production and client assertion accepted by API are examples. explicit , mutually exclusive rules, issuer and audience reduce risk.

jku URLs, x5u, and fields controlled by the token can induce SSRF or key substitution. can cause path traversal or insecure database query when concatenated without validation. The validator must treat headers as hostile input, use preconfigured endpoints, and limit size and characters.

Compression oracle is a risk when secret and attacker-controlled data is compressed before encryption and the size can be observed. RFC 8725 recommends avoiding compression of cryptographic inputs in sensitive scenarios. Tokens also need limits to prevent excessive CPU and memory consumption.

Table 11 - Hardening combines encryption, parsing, networking and governance.
ThreatExampleControl
Algorithm confusionHS256 accepted with material intended for RSA.Allowlist, kty/alg compatibility and mature libraries.
Cross-JWT confusionID Token accepted as access token.type, audience, profile and separate validators.
Key injection / SSRFjku points to controlled host or internal network.Pre-configured endpoints and controlled egress.
ReplayToken copied within validity.Short life, jti where applicable and sender constraint.
Key compromisePrivate key exposed.HSM/KMS, emergency rotation and coordinated withdrawal.
Cryptographic DoSHuge tokens or random kid force refresh.Limits, negative cache, rate limit and circuit breaker.

18.22 Privacy, logging and minimization

A can contain name, email, groups, tenant, identifiers and business data in human-readable text. Recording the full token in access logs, traces, APM, support tools or error messages replicates data and credentials across multiple systems. Even expired tokens can reveal personal information or internal architecture.

Logs must record only necessary fields: normalized issuer, expected audience, , validation result, failure code, non-reversible hash of the jti or subject when allowed and correlation ID. The raw value of the Authorization header must be masked before reaching generic logs.

encryption reduces reading during transport and storage, but the recipient needs decryption and may leak the plaintext into logs. Minimization remains the most efficient control. Authorization claims can also reveal organizational structure; assess need, retention and access.

Observability rule

Collect enough evidence to diagnose without copying credentials. Never post real tokens in tickets, chats, documentation, or online decryption tools.

18.23 Evidence-driven troubleshooting

Diagnosis begins by classifying the fault. Parsing error indicates structure, or JSON. Invalid signature points to key, algorithm, bytes, environment or corruption. Unknown suggests incorrect rotation, cache or issuer. Invalid audience and invalid issuer are semantic, not cryptographic, flaws.

Compare the token with the issuer's metadata without exposing the full value. Record , , , iss, aud, exp and local time. Consult the trusted and confirm kty, usage, key_ops and . Check if the new key is already published and if the old one should still remain. In clusters, compare caches and clocks across instances.

For , separate failure from key management, decryption and tag. Wrong private key, incompatible , invalid IV and changed ciphertext produce different symptoms in the library, but the external response must be generic to not create oracle. Preserve details only in restricted logs.

In gateways, correlate access log, policy trace, metadata metrics, cache and backend. A 401 response can be produced by the gateway, the API, or another proxy. Identify the exact component and step that failed before changing configuration.

Table 12 - Token symptoms point to different pipeline steps.
SymptomInitial hypothesesEvidence
Malformed JWTSegments, Base64url, JSON or size.Part count and parser error.
Invalid signatureWrong key, alg, changed token or environment.Issuer, kid, JWK and bytes received.
Unknown kidWrong rotation, cache or issuer.Current JWKS, cache age and rotation timeline.
Expired / not yet validClock, exp, nbf or tolerance.UTC of all instances and temporal claims.
Invalid audienceToken issued to another resource.aud, requested resource and API configuration.
Decryption failedPrivate key, alg, enc, IV or tag.JWE configuration and restricted internal error.

18.24 Case studies and labs

Case 1 - Intermittent rotation: some instances accept the new and others return 401. Investigation shows local caches with different times and update without coalescing. The fix publishes the key in advance, standardizes caching, adds controlled refresh, and keeps the old key for the maximum validity.

Case 2 - valid token for wrong audience: the gateway verifies the signature of a token issued to the portal and forwards the call to the API. The fix requires API type and audience, separates ID Token and access token validators, and adds negative testing to the pipeline.

Case 3 - key by token URL: A library follows jku and allows the attacker to provide his own key. The fix removes dynamic resolution, fixes metadata per issuer, blocks unnecessary egress and revises already accepted tokens.

Case 4 - sensitive claims in logs: an incident reveals that APM stored complete Authorization. The fix masks the header at the first entry point, reduces claims issued, applies retention and revokes potentially exposed tokens.

Lab 1 - validate a with local library

  • Generate a laboratory key pair in an isolated and authorized environment.
  • Issue a short-lived with iss, aud, exp, and .
  • Validate with algorithm allowlist and pre-configured public key.
  • Change one byte of the payload and observe the cryptographic failure.
  • Change aud without re-signing to compare signature failure and semantic failure.

Lab 2 - simulate rotation

  • Publish K1 and issue tokens with K1.
  • Add K2 to the set before using it for signing.
  • Upgrade signer to K2 and keep K1 available.
  • Observe cache behavior in different instances.
  • Remove K1 only after tokens and operating margin expire.

Laboratory 3 - mandatory negative tests

  • Reject none and algorithm outside the allowlist.
  • Reject incorrect issuer, audience and type.
  • Reject expired, future or excessively large token.
  • Reject unknown without triggering unlimited refresh.
  • Reject unknown and unauthorized remote headers.
  • Reject ID Token presented to the API as an access token.

Laboratory security

Use only dummy keys and tokens. Never copy production credentials to testing tools, decryption sites, or training documents.

Chapter summary

JOSE separates claims, signature, encryption, algorithms and key representation. does not automatically stand for signed token, access token, or secure credential. Trust arises from the combination of valid structure, correct cryptographic operation, key linked to a permitted issuer and semantic validation of the profile.

protects integrity and origin, but keeps the payload readable. protects confidentiality by authenticated encryption and separates , responsible for , from , responsible for content. Nested tokens can combine properties, but increase complexity and need clear profiling.

and rotation are part of the runtime. Early publishing, controlled caching, overlapping, and planned retirement prevent downtime. is just a hint inside the issuer; URLs and keys provided by the token itself should not create trust.

RFC 8725 guides allowlists, mutually exclusive validations, explicit typing, and protection against confusion. RFC 9864 updates the handling of fully specified algorithms, and the IANA registry remains the operational reference for names and status.

Design and operation checklist

  • Is there a documented profile for each supported type?
  • Are issuer, audience, type and algorithms defined by trust configuration?
  • Does validation use the correct issuer key and not a global cache per ?
  • Does have cache, limits, coalesced refresh and tested rotation?
  • Are private keys stored in an HSM, KMS or audited vault?
  • Are algorithms compatible with kty, use and key_ops?
  • Do temporal claims use UTC, clock synchronization and limited tolerance?
  • Do ID tokens, access tokens, client assertions and logout tokens use separate validators?
  • Do jku, x5u, and headers receive safe treatment?
  • Logs mask Authorization and not store full tokens?
  • Do negative tests cover confusion of type, audience, algorithm and rotation?
  • Is there a procedure for committing and emergency key removal?

Review exercises

  • Explain why a successfully decoded is still untrustworthy.
  • Describe the difference between , and using an API example.
  • Calculate which components can issue tokens when HS256 is shared between five APIs.
  • Propose a rotation sequence for tokens with a 20-minute expiry and a 10-minute cache.
  • Explain why cannot identify a key globally.
  • Differentiate and in a with RSA-OAEP-256 and A256GCM.
  • Describe how helps prevent the use of ID Token as an access token.
  • Explain the risk of following jku informed by the token.
  • Compare locally validated token and opaque token with introspection.
  • Define what information can be recorded in logs without copying the credential.

Glossary

Table 13 - Essential vocabulary of the chapter.
TermDefinition
AADAdditional Authenticated Data; authenticated data without being encrypted.
algSignature algorithm, MAC or key management.
Base64urlSecure byte encoding for URLs, without confidentiality.
CEKContent Encryption Key used to encrypt content in JWE.
claims setJSON object containing assertions carried by JWT.
critList of critical parameters that the consumer must understand.
ctyProtected content type, useful in nested objects.
encJWE content authenticated encryption algorithm.
JWAJSON Web Algorithms; identifiers and cryptographic parameters.
JWEJSON Web Encryption; authenticated cryptography framework.
JWKJSON Web Key; JSON representation of a key.
JWKSJSON Web Key Set; set of JWKs.
JWSJSON Web Signature; digital signature or MAC over bytes.
JWTJSON Web Token; set of claims protected by JWS or JWE.
kidKeyID; key selection hint within a context.
Nested JWTJWT protected in multiple layers, like JWS inside JWE.
thumbprintDigest derived from key or certificate for identification.
typType of object declared for application processing.

Annex A - Decision matrix

Table 14 - Architecture depends on the requirement, not just JWT preference.
NeedInitial strategyEssential controls
API validates locallyAsymmetrical JWS and JWKS.Issuer, audience, type, allowlist, cache and rotation.
Immediate revocationOpaque token or introspection.AS availability, short cache and RS authentication.
Confidential ClaimsJWE or opaque reference.Minimization, alg/enc, recipient key and logging.
Multiple validatorsAsymmetric signature.Private only at the issuer and public distributed.
Proof of possessionDPoP or mTLS-bound token.cnf, proof by request, nonce and trusted proxies.
Multiple types of JWTSeparate validators and explicit type.Mutually exclusive rules and negative tests.
Frequent rotationJWKS with planned overlap.Publish before, cache controlled and remove later.
Selective credentialSD-JWT as per RFC 9901.Disclosures, key binding, privacy and specific profile.

Technical references

  • IETF. RFC 7515 - JSON Web Signature ( ). 2015.
  • IETF. RFC 7516 - JSON Web Encryption ( ). 2015.
  • IETF. RFC 7517 - JSON Web Key ( ). 2015.
  • IETF. RFC 7518 - JSON Web Algorithms ( ). 2015.
  • IETF. RFC 7519 - JSON Web Token ( ). 2015.
  • IETF. RFC 7638 - JSON Web Key ( ) . 2015.
  • IETF. RFC 7797 - Unencoded Payload Option. 2016.
  • IETF. RFC 7800 - Proof-of-Possession Key Semantics for JWTs. 2016.
  • IETF. RFC 8037 - CFRG Elliptic Curve Diffie-Hellman and Signatures in JOSE. 2017.
  • IETF. RFC 8725 / BCP 225 - JSON Web Token Best Current Practices. 2020.
  • IETF. RFC 9068 - Profile for OAuth 2.0 access tokens. 2021.
  • IETF. RFC 9101 - OAuth 2.0 -Secured Authorization Request. 2021.
  • IETF. RFC 9278 - URI. 2022.
  • IETF. RFC 9701 - Response for OAuth Token Introspection. 2025.
  • IETF. RFC 9864 - Fully-Specified Algorithms for JOSE and COSE. 2025.
  • IETF. RFC 9901 - Selective Disclosure for JSON Web Tokens. 2025.
  • IANA. JSON Object Signing and Encryption (JOSE) registries.
  • IANA. JSON Web Token Claims registry.
  • Microsoft Learn. Azure API Management validate- and validate-azure-ad-token policies.
  • Axway Documentation. API Gateway validation, signing and encryption filters.
  • OWASP. JSON Web Token Cheat Sheet for Java and OAuth 2.0 Security Cheat Sheet.

Update note

JOSE algorithms, logs and profiles continue to evolve. Before deploying a combination, confirm the current status in the IANA registry, the RFCs that update the specification, and the exact support of the library, HSM, identity provider, and API Gateway.