JWT and JWKS in Production: Building Trust Between APIs
TL;DR
We replaced a shared service credential with short-lived, asymmetrically signed JWTs. The calling API kept its private key; the receiving API obtained public verification keys through JWKS. Each protected operation then checked the caller’s identity, its exact permission and, where applicable, access to the requested object.
The difficult work was defining those boundaries and operating them across web processes, workers, caches and rolling deployments. A successful signature check did not establish ownership. A working JWKS URL in a browser did not establish that the actual verifier could fetch it. Changing a signing key did not establish that every runtime had switched.
The original migration completed eight agreed acceptance stages in both development and production, including bounded rotation and rollback checks. A later change protecting six visitor-facing service operations passed 362 focused local security tests; its deployed acceptance remained pending at the recorded checkpoint. This article explains both, without treating them as the same release result.
Public-example note: service names, domains, key identifiers and routes below are illustrative. The operational measurements retain their original scope. One Node.js example translates the design into executable code; it is not the production implementation.
Jump to the trust boundary, the Node.js example, anonymous visitors, key rotation, discovery failures, or the verification record.
The problem: what did the shared secret actually authorize?
Our browser-facing API called a separate service that handled chat, documents and background processing. I will call them Gateway and Analysis API.
A shared service token made the initial integration straightforward: Gateway attached a credential and Analysis API recognized it. As more operations appeared, we needed a more precise agreement. A document reader, a chat request and a background job should not receive authority merely because they came from code that knew the same secret.
We wanted each request to answer four questions:
- Which service is calling?
- Which operation may it perform?
- Is it acting for a user, and is that user still allowed to access this object?
- If the visitor is anonymous, what proves possession of this particular session?
Those questions became the contract between the APIs. JWT supplied a signed way to carry claims; route and object policies supplied the decisions.
The existing browser login remained separate. We did not turn the user’s login token into a universal credential for every downstream service, and we did not return internal service JWTs to the browser.
Browser ── login credential, or anonymous visitor ──► Gateway
│
service JWT, scoped
│
▼
Analysis API
│
fixed, trusted JWKS endpoint
│
▼
Gateway public keys
Gateway issued the service token inside its own process. There was no browser token exchange or new public token-minting endpoint. This was an application-owned issuer; the design does not require every team to operate its own issuer instead of using an existing identity platform.
What JWT and JWKS each contribute
A JWT carries claims such as issuer, audience, subject and expiration. In this design it is signed, not encrypted: the signature protects integrity, while the payload remains readable. Transport encryption and careful token handling are still necessary. RFC 7519 defines the token and registered claims.
A JWK represents a key as JSON. A JWKS is a JSON object containing a keys array. Our discovery response contained only public verification material. The kid in the token header selected a key from that trusted set; it did not make the key trustworthy by itself. RFC 7517 defines that representation.
We used RS256 and generated 3072-bit RSA keys for the rollout. Gateway could sign; Analysis API could verify without receiving the private key. That reduced the places holding signing authority. It did not make a compromised issuer harmless: an attacker controlling the signer could still mint credentials within the verifier’s accepted policy.
The verification policy fixed the expected algorithm, issuer and audience. A token could not choose a different algorithm or send the verifier to its own key URL. The endpoint was trusted deployment configuration, independent of unverified claims. These decisions follow the algorithm, issuer and audience checks in JWT Best Current Practices.
Record the clocks separately
Several settings looked similar in configuration but governed different events:
| Recorded setting | Value | What it controlled |
|---|---|---|
| Issued service-token lifetime | 300 seconds | How long Gateway’s newly issued tokens were intended to remain valid, before clock tolerance. |
| Verifier clock tolerance | 30 seconds | The accepted time-boundary allowance. |
| Verifier JWKS cache lifetime | 300 seconds | When that verifier’s cached key set became stale. |
| JWKS HTTP freshness | 60 seconds | The publisher’s HTTP cache policy; separate from the library’s internal cache. |
| JWKS fetch timeout | 3 seconds | The configured network wait bound for discovery. |
| Verifier maximum accepted token lifetime | 3,600 seconds | The historical acceptance ceiling, distinct from the issuer’s observed 300-second output. |
These are measured configuration values, not recommended defaults for every system. In particular, a five-minute issuer TTL does not prove that the receiver rejects a correctly signed one-hour token. The runnable example below deliberately uses a stricter five-minute acceptance ceiling; it does not claim that we changed the historical production setting.
One Node.js example: issue a credential, then enforce a policy
The example uses jose for the cryptographic operations. The application code defines the trust agreement and permission checks.
The core signing and receiving checks look like this. These are excerpts from one complete example: the issuer runs in Gateway, the verifier in Analysis API. They share a trust agreement, not the private key.
// Gateway: select the operation in trusted route code, then issue its scope.
// ISSUER = "https://gateway.example.com", AUDIENCE = "analysis-api"
// SERVICE = "gateway", TOKEN_SECONDS = 300, CLOCK_TOLERANCE_SECONDS = 30
return new SignJWT({
actor_type: 'service',
service_identity: SERVICE,
scope: scopeFor(operation),
})
.setProtectedHeader({ alg: 'RS256', typ: 'JWT', kid })
.setIssuer(ISSUER)
.setAudience(AUDIENCE)
.setSubject(SERVICE)
.setIssuedAt(now)
.setNotBefore(now)
.setExpirationTime(now + TOKEN_SECONDS)
.sign(privateKey);
// Analysis API: verify against its configured JWKS resolver.
// guardedResolver requires kid and distinguishes discovery failures.
({ payload } = await jwtVerify(token, guardedResolver, {
algorithms: ['RS256'],
issuer: ISSUER,
audience: AUDIENCE,
subject: SERVICE,
typ: 'JWT',
requiredClaims: ['exp', 'iat', 'nbf', 'actor_type', 'service_identity', 'scope'],
maxTokenAge: TOKEN_SECONDS,
clockTolerance: CLOCK_TOLERANCE_SECONDS,
currentDate: clock(),
}));
// A maximum token age alone does not cap the encoded expiration window.
if (payload.exp <= payload.iat || payload.exp - payload.iat > TOKEN_SECONDS
|| payload.nbf >= payload.exp) {
throw new AuthenticationError();
}
// This route accepts one service-only workload, not delegated user context.
if (payload.actor_type !== 'service' || payload.service_identity !== SERVICE
|| payload.scope !== requiredScope
|| ['user_id', 'on_behalf_of', 'tenant_id']
.some((key) => Object.hasOwn(payload, key))) {
throw new AuthorizationError();
}
Here postChat maps to public-chat:write, and readCard to public-chat:read. Each token carries exactly one of these permissions. A correctly signed read token therefore cannot authorize the write operation.
The complete Node.js example includes the signer, persistent remote resolver, error handling, pinned dependency and executable tests. Its implementation and test suite are also available directly. From that directory, run npm ci --ignore-scripts and npm test with Node.js 24 or later.
The 20 tests passed using generated 3072-bit RSA keys, local JWKS fixtures and a stubbed network client. They cover valid calls, tampering, wrong algorithms and identities, missing claims, time boundaries, exact permissions, key lookup and discovery failure. No production credentials or network access are needed; no private keys or bearer tokens are printed. These are tests of this example, separate from the historical rollout results below.
The receiving route chooses the required operation from its own registry. It must not accept a request parameter such as required_scope and let the caller choose an easier check. Likewise, the signing code derives scope and identity from trusted application context, not arbitrary browser-supplied claims.
Create the remote JWKS resolver once per process so its cache and refresh coordination survive individual requests. Its URL is fixed HTTPS configuration. An unknown kid can trigger a bounded refresh according to the library’s cooldown policy; it must not trigger an unrestricted outbound fetch to a token-provided address. The library documents these behaviors in createRemoteJWKSet.
This example covers a service-only policy. A complete API still needs strict credential extraction, response mapping, request/body limits, session-capability checks and domain authorization. Reject duplicate or conflicting credentials at the HTTP boundary, and never turn failed verification into an anonymous retry.
A valid signature is the start of authorization
For an authenticated user request, Gateway first established the user through its normal login flow. It could then issue a short-lived service JWT carrying explicitly permitted delegation. Analysis API checked the service and scope before resolving current user, tenant and object access.
For example, a signed request to read document 123 can be cryptographically valid while the document belongs to another company. The signature establishes that the trusted issuer made the claim. It does not turn the document into an authorized object.
We kept these responsibilities distinct:
| Check | Question it answers |
|---|---|
| Signature, issuer, audience and time claims | Is this a credential accepted by this API’s trust contract? |
| Service identity and route scope | May this caller perform this operation? |
| Current user, tenant and object policy | May this actor act on this resource now? |
| Anonymous-session capability | Does this request possess the credential for this visitor session? |
The same distinction mattered in supported user-initiated background jobs. Queuing a request did not freeze the user’s authority forever. A worker restored trusted identity references and checked current access before obtaining a fresh token and dispatching the operation. Copying an old browser JWT into a queue would have coupled execution to a different credential’s lifetime and semantics.
The issuer also limited scopes by execution profile: visitor-chat grants belonged to web callers, not worker or operator profiles. These were issuance rules within one service identity, not separate cryptographic identities. The operation registry named exact permissions and failed closed for unknown requests.
Public visitors can still use authenticated internal services
The word public initially covered two different things: a visitor could use a product without logging in, and a downstream endpoint could accept a request without a service credential.
Those are separate choices. In the later visitor-policy work, the intended flow became:
Visitor → Gateway: anonymous; session capability on reuse
Gateway → Analysis API: service JWT + capability on reuse
Analysis API → Visitor, through Gateway: result; capability on creation
Adding a JWT at Gateway alone would not establish that boundary. If Analysis API still declared the route anonymous, a direct caller could omit the token. We therefore changed both the caller’s operation registry and the receiver’s route policy.
Six operations used four explicit grants:
| Operation | Required service grant |
|---|---|
| Send a public-chat message; delete a session | public-chat:write |
| Read a saved session card | public-chat:read |
| Upload or delete a public-session attachment | attachments:public:write |
| List public-session attachments | attachments:public:read |
The receiver also required the designated Gateway service identity without user delegation or tenant context for these visitor operations. A different service carrying the same scope was insufficient.
A session capability answered the remaining possession question. It was a separate bearer credential for one anonymous session, with its own signing and enforcement configuration. Initial creation had no earlier capability to supply; subsequent operations needed the issued capability when that control was enabled. A session ID alone was not intended to serve as proof of possession.
This separation also kept the rollout honest. JWT enforcement did not automatically activate capability enforcement, and existing sessions that had never received a capability needed an agreed restart or migration policy. The six-route change had local coverage at the checkpoint used here; complete browser and deployed capability acceptance remained work to do.
Generic health and narrow aggregate job metrics stayed explicitly public. Detailed job operations remained protected. This mattered operationally: an autoscaler reading aggregate counters should not suddenly need an interactive user’s credential. We changed the consumer contract deliberately instead of treating an entire URL prefix as public.
Key rotation is a distributed rollout
The basic rotation sequence fit on one line. Proving that it had happened across every relevant process took considerably more work.
Publication Signing
Normal [K1] K1
Prepublish [K1, K2] K1
Switch [K1, K2] K2
Rollback rehearsal [K1, K2] K1
Retire test key [K1] K1
Our exercise included rollback, so it ended on the original key. In a normal forward-only rotation, the final state would publish and sign with K2 after K1’s retention period.
The reusable sequence was:
- Generate the new key outside the repository and publish both public keys.
- Check discovery with the real verifier client, including its cached-old-key behavior.
- Switch the private signer and its
kidas a matching pair. - Verify issuance and authenticated calls from every relevant web, worker and scheduler runtime.
- Keep both public keys while old-signer tokens can still be accepted and while the agreed rollback path needs them.
- Stop old issuance, wait the retention interval, retire the old public entry and verify refreshed discovery.
The wait begins at the last possible old issuance
Our measured recipe retained the retiring public key for:
300 s observed issued-token lifetime
30 s configured clock tolerance
90 s rollout safety margin
─────
420 s, or seven minutes, after the last possible old-key issuance
The timer did not begin when an operator first saved a secret. A remaining worker with the old signer could issue a new token later. We needed the runtime inventory and actual issuance checks before recording the cutoff; renewed old-key issuance would reset it.
That seven-minute calculation was specific to the observed issuers, clock assumptions and rollout. A different accepted token population, a longer TTL or a later old-signer process would change it. Publication propagation and verifier caching also need their own checks. Removing a key from the published set does not instantly remove every verifier’s cached copy.
Our deployment tool updated one environment variable per restart. Saving the private key and key ID separately could temporarily leave them mismatched. We accepted that limitation for the exercise. We also observed a transient issuance failure during rollout, although its exact cause was not established. The evidence supports switch, rollback and retirement checks; it does not support a zero-downtime rotation claim. An uninterrupted rollout needs coordinated signer configuration and readiness checks for the matching pair.
At the final production retirement checkpoint, five caller runtimes passed current-signer checks. Two fresh diagnostic clients, one in each receiving API replica, refreshed the real JWKS and rejected selection of the retired key. Those clients did not inspect or evict every cache inside the serving application processes, and the check was not an HTTP request carrying a retired-key JWT.
Retiring publication is not destroying the backup
The private signing key belongs in a managed secret store or signing service with controlled access and an explicit recovery owner. Public JWKS can be distributed to verifiers; private PEM must not be included in it. Keep development and production key material separate.
Retain previous private material only for the approved rollback or incident-recovery period. The public-key overlap calculation does not decide when to destroy a recovery backup. Keep private keys and bearer tokens out of logs and chat attachments. Public JWKS can be shared openly; reviewed deployment artifacts make changes to that trust set auditable.
Suspected key compromise needs a separate response that stops affected issuance and addresses trust removal and verifier caches. The ordinary overlap interval is not an emergency-revocation guarantee.
Key discovery became an availability dependency
JWKS let the receiver verify credentials without sharing signing authority, but discovery introduced another path that had to work under real network and application conditions.
A browser 200 did not prove the verifier worked
During production setup, one HTTP client fetched the public keys successfully while the actual verifier received 403. A controlled comparison reproduced an edge rejection when using the verifier client’s User-Agent; the internal request succeeded.
The edge rejected the machine client’s browser signature. We prepared a narrowly scoped Browser Integrity Check exception for the public key route and its read methods. Cloudflare documents this class of failure as error 1010, browser-signature denial.
The lesson was practical: test discovery from the receiving runtime with its real library, trust settings, headers and URL. A laptop, browser or unrelated HTTP client can take a different path.
A controller without SQL still depended on the database
A later local reproduction found database-backed feature-flag middleware preloading state before the public-key controller ran. The controller itself needed no database. The surrounding request stack did.
Earlier tests used an in-memory feature adapter and missed that dependency. With the production-like adapter, the focused reproduction had six failures in 54 examples. The repair skipped automatic preload only for the exact JWKS read route, preserving other feature behavior. The combined regression selection then passed 306 examples.
That established a concrete local defect and repair. It did not prove that every historical production 500, edge 403 or discovery timeout came from the same cause. Status, timestamp, serving replica and the exception at the emitting layer were still necessary to attribute an individual incident.
For a key endpoint, inspect everything before and around the handler: session loading, feature stores, rate-limit storage, redirects, proxy rules and caches. Removing one unnecessary dependency should not silently disable protections on unrelated routes.
Fail closed, and preserve the reason
We distinguished an unacceptable credential from an inability to obtain the keys needed to evaluate it:
| Condition | Application behavior in this design |
|---|---|
| Missing, malformed, expired or invalidly signed token | 401; no protected handler work. |
| Valid accepted identity, insufficient scope or disallowed actor context | 403; no protected handler work. |
| Missing or wrong session capability, with capability enforcement enabled | Existing non-disclosing 404 behavior. |
| Required JWKS discovery unavailable | Sanitized 503; never retry the protected operation anonymously. |
A valid key already in an acceptable cache can allow verification without a fetch. Cache-miss and cache-expiry behavior must therefore be tested separately. One controlled failure test returned a sanitized 503 in 3.02 seconds under a configured three-second timeout. That was an isolated check with substituted dependencies, not a production latency percentile or availability guarantee.
Useful telemetry records the failure category, route, runtime, deployment revision, elapsed time and correlation ID. Full bearer tokens, private keys and unrestricted claim dumps do not belong in those logs. Discovery failures, signature failures and authorization denials need different operational responses.
Internal transport is a separate control
We documented a follow-up to keep service calls and key discovery on internal service addresses protected by verified mesh mTLS. Application JWT authorization would remain: peer transport identity does not replace route scopes or object policies.
That cutover was not accepted in the recorded work. An infrastructure report that mTLS exists is not proof that every relevant connection requires it. The plan requires effective policy and peer-identity evidence, no plaintext bypass, compatible URL validation and checks from actual replicas. Only after that succeeds should the temporary public-edge exception be retired.
What we tested—and what the results establish
A positive test showed that one request could succeed. Negative controls established which part of the agreement was actually enforced.
We exercised wrong issuer and audience, expired and future-dated tokens, invalid signatures, unsupported algorithms, unknown and missing key IDs, conflicting credentials, insufficient scopes and cross-owner/tenant access. Public health and aggregate metrics had explicit anonymous checks. Workers needed their own checks rather than inheriting a web-process result.
The result ledger kept different kinds of evidence separate:
| Evidence | Recorded result | Limit |
|---|---|---|
| Original development and production rollout | Eight agreed stages completed in each environment in October 2026 | Bounded acceptance of that migration, not every later authorization change. |
| Production extended HTTP negative-control batch | 18/18 passed; additional missing/tampered/scope checks ran across callers | Not a claim that every possible token or route combination was tested. |
| Isolated failure exercises using deployed classes | 32/32 passed | Child-process tests with substituted dependencies; no deliberate production database or network outage. |
| Production rotation/rollback retirement checkpoint | Five caller runtimes and two refreshed diagnostic verifier clients checked | No proof of uninterrupted rotation, immediate revocation or all serving-cache contents. |
| Later visitor-service policy extension | 362 focused local security tests passed | Deployed visitor/capability acceptance pending at the December 1 checkpoint. |
| Database-backed E2E selection for that extension | 176 tests collected | Not executed; safe local database and Redis setup was still required. |
| Key-route database-independence repair | Six initial regression failures corrected; combined 306-example selection passed | Local production-like middleware tests; no newly established production-outage recovery. |
These selections overlap; their counts should not be added into a security score. Nor does a large general regression suite measure the strength of the authorization model. The value is knowing which behavior was checked, against which code and at which boundary.
We kept reusable synthetic fixtures and acceptance scripts with the runbook. Each deployed run needed its own environment, source/image identity, runtime inventory, timestamps and results. A merged PR, a successful image build, a healthy pod and an authenticated product request were separate checkpoints.
The rollout order also became part of the security contract: publish usable keys and deploy capable callers before requiring their credentials at the receiver. For the visitor extension, Gateway had to be deployed first. Turning enforcement off to make an old caller work would erase the property the change was intended to establish.
What I would carry into the next API integration
I would start with the caller and operation map, then choose the token and key-delivery mechanism. That makes it easier to see where service identity ends and user, tenant or session authority begins.
I would also put the operational exercises next to the implementation from the start: real-client discovery, unknown-key refresh, matching signer configuration, worker coverage, rollback and dependency failure. They found problems that a successful signature unit test could not reveal.
The resulting system had explicit trust decisions and a repeatable way to check them. Its remaining work stayed visible: visitor capability activation and deployed acceptance, older-session handling, and the internal transport cutover. That is the experience I would reuse—along with the working verifier code—when the next service joins the architecture.