CLIENTS · REDIRECTS · TOKENS · SIGNATURES · SESSIONS · DPOP

OAuth and JWT:
how one sign-in becomes an API call

OAuth lets one app use your account on another service without ever seeing your password. You say yes once, on the other service’s own page, and the app gets a token: a string that opens only what you allowed, for a few minutes at a time.

You click Import from Photos on a print shop’s site. Your browser goes to the photo service, you sign in there and press Allow, and you come back to the print shop, which can now list your 48 photos. You order 12 prints and close the tab, and the print shop downloads the originals later without you. Each chapter adds the part of OAuth that makes one of those things possible, and shows what someone holding a copy of a token can and can’t do with it.

Here is the whole setup. Most boxes won’t mean much yet; each chapter explains one of them.

MapThe browser carries the redirects; the print shop’s server makes every other call.

You need to know HTTP requests, redirects and cookies; no OAuth experience is assumed. Every value comes from one run of the open-source sign-in server oidc-provider 9.15.0 and two small Python apps on a laptop on 16 November 2026, all on localhost over plain HTTP. Anywhere else, every one of these requests must be HTTPS. Code samples are Python. Tap any figure to open it full screen and zoom. Dotted terms are tappable.

Four roles instead of one password

The print shop wants to read photos from your photo library, and the simplest way to let it is to type your photo-service password into its form. For years that is how apps did it. OAuth splits the job between the photo service and the app instead, so the password never leaves the photo service. How can the print shop read your photos without ever seeing your password?

STEP 01 / 04

OAUTH SPLITS ONE LOGIN INTO FOUR ROLES

Fig 1.1Four boxes, one job each. The photo service runs two: one checks passwords, the other holds photos. Faint parts arrive later.

OAuth 2.0 (RFC 6749) splits one login into four roles. You are the resource owner: the photos are yours. The print shop is the client, the app asking for access, and here that means its web server. Your browser only carries you between the sites.

The photo service runs the other two. Its authorization server, called the sign-in server here (localhost:8080), is the only one that ever sees your password, and it issues tokens. Its resource server, the photo API (localhost:4000), holds the 48 photos and accepts tokens.

A token works like a car’s valet key: it starts the engine and doesn’t open the boot. The rest of the tutorial adds, one chapter at a time, the parts that make that true.

STEP 02 / 04

A PASSWORD HANDS OVER EVERYTHING, FOR GOOD

Fig 1.2Read across each row. The accent row is the one a password can’t answer: taking access back from one app.

Typed into the print shop’s form, your photo-service password lets the print shop do everything you can do: read all 48 photos, delete them, change your email address. To use it again tomorrow, the print shop has to store it, so your password now sits in someone else’s database.

It keeps working until you change it, and changing it locks out every other app you gave it to. The print shop needs one permission, reading photos, for a short time. A token carries exactly that, for 300 seconds, and can be taken back from this one app.

STEP 03 / 04

THE PRINT SHOP REGISTERS BEFORE IT ASKS

Fig 1.3The accent row is the only address the sign-in server will ever send this app’s codes to.

Before anyone signs in, the print shop is registered with the sign-in server. It gets a client_id, print-shop, and declares the one redirect URI where you may be sent back after signing in: http://localhost:3000/callback.

The record also lists the grant types it may use and how it proves its identity later, client_secret_basic, which chapter 03 explains. The sign-in server compares every redirect URI it is given with this list, character for character.

STEP 04 / 04

A SCOPE IS ONE NAMED PERMISSION

Fig 1.4Each row is one scope the print shop asks for. The accent row is the only one the photo API ever checks.

A scope is a named permission that the client asks for and you approve. The print shop asks for 5: openid, profile and email are about who you are (chapter 06), and offline_access lets it work while you are away (chapter 07).

Only photos:read is checked by the photo API. The sign-in server lists every scope on its Allow page, and the token it issues carries the ones you approved.

COMMON QUESTIONS

Is OAuth a way to sign in?
No. OAuth gives an app access to an API. Signing in is OpenID Connect, a layer on top, which chapter 06 adds.
Is my browser the client?
Here, no: the client is the print shop’s web server. An app that runs entirely in the browser is a client too, a public one, and chapter 03 shows what changes.
Does my own app’s login need OAuth?
Not when the app and its API are one site with its own accounts. OAuth earns its place when a second party holds the data or the passwords.

WHAT YOU NOW KNOW

  • A password gives the print shop everything you can do, until you change it, and you can’t take it back from just one app.
  • OAuth splits the photo service into a sign-in server that sees your password and an API that only accepts tokens.
  • The print shop is registered with one exact redirect URI, and of its five scopes only photos:read matters to the photo API.
DEEP DIVE: OAuth 1.0, OAuth 2.0’s bet on TLS, the password grant and OAuth 2.1

OAuth 1.0

In November 2006 Blaine Cook, working on Twitter’s OpenID sign-in, and Chris Messina looked for an open way to delegate API access and found none. OAuth Core 1.0 is dated 4 December 2007. It signed every request with a shared secret, so it worked over plain HTTP.

OAuth 2.0’s bet

RFC 6749 and RFC 6750 (both October 2012) dropped per-request signatures and relied on TLS instead: a token sent in a header, called a bearer token. Eran Hammer, editor of the earlier drafts, resigned in June 2012. He wrote that 2.0 was “more complex, less interoperable, less useful, more incomplete, and most importantly, less secure”. Chapter 09’s DPoP brings per-request signatures back, for a different reason.

The password grant

OAuth 2.0 included a “resource owner password credentials” grant, in which the app collects your password and sends it to the token endpoint itself. RFC 9700 (January 2025) says it must not be used.

OAuth 2.1

The OAuth 2.1 draft (draft 17, 31 October 2026, not yet an RFC) folds a decade of fixes into one document. It omits the password grant and the implicit grant, and requires PKCE and exact redirect URIs.

Your yes, on the provider’s page: the authorization endpoint

The print shop has a button, Import from Photos, and no right to read anything. It needs your yes, and the yes has to be given to the photo service, on the photo service’s own page, where the password form is. Your browser has to get there and back, and the print shop must be sure the answer belongs to the sign-in it started. How does your browser get to the sign-in server and back, and what does it bring with it?

STEP 01 / 05

THE BROWSER CARRIES YOU TO THE AUTHORIZATION ENDPOINT

Fig 2.1The accent arrow is the front channel: out through the browser to /auth, and back to the print shop with a code.

The authorization endpoint, /auth on the sign-in server, is where every OAuth sign-in starts. Your browser reaches it by a redirect, sees the sign-in and Allow pages there, and is redirected back to the print shop’s /callback.

This route through your address bar is the front channel: every value on it travels in a URL you can see. The map adds /auth, the grant it stores, and the round trip.

STEP 02 / 05

ONE REDIRECT CARRIES THE WHOLE REQUEST

Fig 2.2One row per parameter of the redirect. The accent row says where your browser will be sent back to.

Your click sends GET /connect to the print shop. The answer is 302 Found: no page, only a Location header telling your browser to go to http://localhost:8080/auth with 10 query parameters, 374 characters in all.

response_type=code asks for a code back, client_id names the print shop, redirect_uri says where to send you, and scope lists the five permissions. state and nonce are random values checked later; code_challenge belongs to chapter 03 and resource to chapter 04.

THE PRINT SHOP’S /CONNECT HANDLER: BUILD THE SIGN-IN URL
import secrets
from urllib.parse import urlencode

session = {
    "state": secrets.token_urlsafe(16),  # checked when you come back
    "nonce": secrets.token_urlsafe(16),  # checked inside the ID token
}
params = {
    "response_type": "code",
    "client_id": "print-shop",
    "redirect_uri": "http://localhost:3000/callback",
    "scope": "openid profile email photos:read offline_access",
    "state": session["state"],
    "nonce": session["nonce"],
    "code_challenge": code_challenge,  # from the PKCE sample
    "code_challenge_method": "S256",
    "resource": "http://localhost:4000",  # the photo API: becomes the token's aud
    "prompt": "consent",
}
location = "http://localhost:8080/auth?" + urlencode(params)  # sent as a 302
STEP 03 / 05

THE PASSWORD GOES TO ONE SERVER ONLY

Fig 2.3Follow 1 to 9 down the page. Only the first and last reach the print shop; the accent one carries your password.

9 browser requests make the round trip, and the print shop receives only the first and the last. In between, 303 See Other redirects move the browser through the sign-in form, where your email and password are posted to localhost:8080, and then the Allow page.

While you type, the address bar shows localhost:8080, which is how you can check where the password goes. The print shop’s scripts can’t read a form on another origin, so they never see it either.

STEP 04 / 05

“ALLOW” IS STORED AS A GRANT

Fig 2.4The page on the left is what you saw. The accent card is the record that pressing Allow created.

Signing in and allowing are separate pages. The Allow page lists what the print shop asked for, and pressing Allow is your consent: a yes to one app, given on the photo service’s own page.

The sign-in server stores it as a grant: one record linking your account 248289761001, the client print-shop and the scopes you approved. Every token issued from now on points back to that record, which is why chapter 07 can cancel all of them at once.

STEP 05 / 05

THE CODE COMES BACK, AND STATE PROVES WHO ASKED

Fig 2.5Read the callback left to right. The accent checks pass for your callback; the attacker’s callback below fails the state check.

The last redirect sends your browser to /callback?code=…&state=…&iss=… on the print shop. The authorization code is 43 characters that open nothing by themselves: it lasts 60 seconds, works once, and needs a value your browser never carried, which chapter 03 shows.

Before redirecting you, the print shop stored a random state value, 22 characters, in your session. The callback must bring it back unchanged, and iss (RFC 9207) must name this sign-in server. A callback from a sign-in someone else started fails with 400 state mismatch.

COMMON QUESTIONS

Is a pop-up window safe for the sign-in page?
Yes. A pop-up keeps its own address bar and runs the same redirects. An iframe is the one to avoid.
What happens if I press Deny?
The sign-in server redirects back to the callback with error=access_denied and no code, and the print shop shows its own message.
Can a redirect URI use plain HTTP?
Only on localhost, as here. Everywhere else the redirect URI must be HTTPS, because the code travels in it.

WHAT YOU NOW KNOW

  • The print shop answers your click with a 302 to /auth: one URL with 10 parameters, 374 characters, and no page of its own.
  • The sign-in server alone receives your password, and it stores your Allow as a grant for print-shop.
  • You come back with a 43-character code that lasts 60 seconds, and the print shop checks the state it sent you with.
DEEP DIVE: exact matching, Covert Redirect, pushed authorization requests and consent phishing

Exact matching

RFC 9700 and the OAuth 2.1 draft require the sign-in server to compare a redirect URI with the registered one by exact string. The one exception is the port of a native app’s loopback address, which the app picks at run time.

Covert Redirect (May 2014)

Wang Jing showed that an open redirector on a client’s own domain could forward a code or token to an attacker. Vendors called it a known issue; RFC 9700 now says clients must not expose open redirectors.

Keeping parameters out of the URL

Pushed Authorization Requests (RFC 9126, September 2021) let the client POST the 10 parameters to the sign-in server first and put only a short request_uri in the browser’s URL, so nothing in the address bar can be edited. This run’s sign-in server offers it at /request, and the print shop doesn’t use it.

Consent phishing

An attacker doesn’t need to steal a token if you grant one. In December 2022 attackers posed as real companies to get the “verified publisher” badge on malicious Microsoft OAuth apps (MSRC, 31 January 2023). In December 2023 Microsoft reported 17,000 multitenant OAuth apps used to send more than 927,000 phishing emails. The Allow page is your only check, so read it before you press Allow.

A code for tokens: the token endpoint and PKCE

The print shop now has a 43-character code from your address bar and still can’t read a single photo. The code is a claim ticket, and the tokens are handed over somewhere the browser never goes: one request from the print shop’s server straight to the sign-in server at localhost:8080. Anyone who copied the code has to be refused there. How does a one-time code become tokens, and why is a stolen code worth nothing?

STEP 01 / 04

A BACK CHANNEL STRAIGHT TO THE TOKEN ENDPOINT

Fig 3.1The accent arrow never touches the browser. It starts on the print shop’s server and ends at /token.

The token endpoint, /token on the sign-in server, swaps a code for tokens. The request goes from the print shop’s server straight to the sign-in server, with no browser in between: the back channel.

The answer lands in the print shop’s session record, on its own server. The map adds /token, the back-channel arrow, and the session record with the three tokens it now holds.

STEP 02 / 04

ONE POST, THREE TOKENS

Fig 3.2The request is on top, the response below. The accent field is the token the photo API will see.

POST /token carries a form: grant_type=authorization_code, the code, the same redirect_uri as before, the PKCE code_verifier (step 4) and the resource the token is for. The answer is JSON with 6 fields.

The access token, the credential the photo API accepts, is 702 characters and lasts 300 seconds. The ID token is 670 characters and the refresh token 43. Everything here is plain HTTP only because all three servers share one laptop; RFC 6749 requires TLS on this endpoint.

THE PRINT SHOP’S SERVER SWAPS A CODE FOR TOKENS
import httpx

resp = httpx.post(
    "http://localhost:8080/token",
    auth=("print-shop", CLIENT_SECRET),  # HTTP Basic: the client authenticates
    data={
        "grant_type": "authorization_code",
        "code": code,  # from /callback?code=...
        "redirect_uri": "http://localhost:3000/callback",
        "code_verifier": session["code_verifier"],  # the PKCE original
        "resource": "http://localhost:4000",
    },
)
tokens = resp.json()
tokens["token_type"]     # 'Bearer'
tokens["expires_in"]     # 300 seconds
tokens["access_token"]   # a JWT for the photo API
tokens["id_token"]       # a JWT for the print shop
tokens["refresh_token"]  # an opaque string, only ever sent back to /token
STEP 03 / 04

A SECRET ONLY A SERVER CAN KEEP

Fig 3.3Compare the columns. The accent row is what each kind of app sends to /token to prove it is itself.

The request carries Authorization: Basic: the client id print-shop and its 34-character client secret, agreed when the print shop registered. It tells the sign-in server that the request comes from the print shop’s own server, not from someone holding a copied code.

That works because the print shop is a confidential client: its code runs on a server you can’t read. An app that runs on your phone or in your browser is a public client. Anyone can unpack its code and find any secret inside, so it is given none.

STEP 04 / 04

A HASH FIRST, THE ORIGINAL LATER

Fig 3.4The hash travels through the browser, the original server to server. The accent check compares them; the attacker has only the code.

Before redirecting you, the print shop made a random code_verifier of 43 characters and kept it in its session. Only its SHA-256 hash, the code_challenge, went into the sign-in URL. That is PKCE, Proof Key for Code Exchange (RFC 7636, September 2015).

At /token the print shop sends the verifier itself. The sign-in server hashes it, compares the result with the challenge it stored, and issues tokens only if they match. Someone who copied the code from a log or a URL never saw the verifier and gets 400 invalid_grant. RFC 9700 requires PKCE for public clients; the OAuth 2.1 draft requires it for every client.

A PKCE VERIFIER AND ITS CHALLENGE
import base64
import hashlib
import secrets


def b64url(raw: bytes) -> str:
    return base64.urlsafe_b64encode(raw).rstrip(b"=").decode()


# 32 random bytes become 43 characters: the shortest verifier RFC 7636 allows
code_verifier = secrets.token_urlsafe(32)
code_challenge = b64url(hashlib.sha256(code_verifier.encode()).digest())

# the challenge goes out in the sign-in URL, through the browser
print("code_challenge", code_challenge)  # 43 characters
# the verifier stays on the print shop's server until the token request
print("code_verifier ", code_verifier)  # 43 characters, never in a URL

COMMON QUESTIONS

Why not send the tokens back in the redirect?
OAuth 2.0’s implicit flow did, in the URL fragment, where browser history and page scripts can read them. The OAuth 2.1 draft removes it.
What if the same code is sent twice?
It is refused, and RFC 6749 says the server should revoke every token already issued from it.
Does a confidential client need PKCE too?
The OAuth 2.1 draft says yes. A secret proves which app is asking; PKCE proves it started this sign-in.

WHAT YOU NOW KNOW

  • One back-channel POST to /token returns a 702-character access token, a 670-character ID token and a 43-character refresh token.
  • The print shop proves it is the print shop with a 34-character client secret, which only a server-side app can keep.
  • PKCE adds proof that it started this sign-in, so a copied code alone gets 400 invalid_grant.
DEEP DIVE: how a client proves who it is, PKCE’s plain method, and what Bearer means

How a client proves who it is

client_secret_basic is this run’s: the secret in an HTTP Basic header. client_secret_post puts the same secret in the form body. private_key_jwt has the client sign a short JWT with its own private key, so no shared secret is ever sent, and mutual TLS (RFC 8705) uses a client certificate. The run’s discovery document lists 5 methods, including none for public clients.

Why the plain method went

RFC 7636 also allowed code_challenge_method=plain, where the challenge is the verifier itself, for clients that couldn’t compute SHA-256. Anyone who sees the sign-in URL then has the verifier. The OAuth 2.1 draft drops it, and the run’s server supports only S256.

What “Bearer” means

RFC 6750 (October 2012) defines the Bearer token type: whoever presents the token may use it, with no further proof. token_type: Bearer in the token response is that rule, and chapter 09 replaces it with DPoP.

A token anyone can read: the JWT

The print shop now holds three strings, and two of them start with the same three letters, eyJ. The access token is the one the photo API will accept, and nobody has looked inside it yet. You can read it without any key, which raises the obvious problem: if anyone can read it, what stops anyone from editing it? What is inside the access token, and what stops someone changing it?

STEP 01 / 05

ONE PRIVATE KEY SIGNS EVERY TOKEN

Fig 4.1The accent key on the sign-in server signed the accent token in the print shop’s session record.

The access token is a JWT, a JSON Web Token (RFC 7519): a few fields of JSON plus a signature. The sign-in server signs every token with a private key, photos-2026-11, that never leaves the sign-in server.

The map adds that key and redraws the token in the print shop’s session record as what it is. The next steps open it.

STEP 02 / 05

TWO DOTS, THREE PARTS

Fig 4.2The bar is the access token drawn to scale. The accent dots are the only two characters that aren’t base64url.

A JWT is three base64url strings joined by two dots. In this one the header is 71 characters, the payload 287 and the signature 342; with the two dots that makes 702.

Base64url is base64 with - and _ in place of + and /, and without the = padding, so a token passes through a URL or a header unchanged. JSON opens with {", which base64url turns into eyJ.

STEP 03 / 05

THE HEADER NAMES ITS OWN KEY

Fig 4.3The header, decoded. The accent row is the one a verifier must never take on trust.

Decoded, the header is JSON with 3 fields. alg RS256 says the signature is RSA over a SHA-256 hash. typ at+jwt says this is an access token (RFC 9068). kid photos-2026-11 names the key that signed it.

A verifier uses kid to pick a key, but it must choose alg for itself, because whoever made the token wrote the header. Chapter 05 sends the photo API three forged tokens, two of them with headers that lie.

STEP 04 / 05

WHO, FOR WHOM, UNTIL WHEN

Fig 4.4Each row is one claim from the payload. The accent pair is the 300 seconds this token is good for.

The payload is 215 bytes of JSON with 8 claims. iss is who issued it, sub whose account (248289761001), aud which API it is for (http://localhost:4000), client_id the app that asked, and scope what it allows.

iat and exp are the issue and expiry times, 10:45:57 and 10:50:57, 300 seconds apart. jti is this token’s own id. There is no name, email or password: the API needs to know whose photos to return, and an account number answers that. The sample reads it all with no key.

READING A JWT WITH NO KEY AT ALL
import base64
import json
import sys

access_token = sys.argv[1]  # the 'eyJ...' string from the token response


def b64url_decode(part: str) -> bytes:
    return base64.urlsafe_b64decode(part + "=" * (-len(part) % 4))


header, payload, signature = access_token.split(".")
print(json.loads(b64url_decode(header)))   # {'alg': 'RS256', 'typ': 'at+jwt', 'kid': ...}
print(json.loads(b64url_decode(payload)))  # every claim, readable without any key
print(len(b64url_decode(signature)))       # 256 bytes: one RSA-2048 signature
STEP 05 / 05

SIGNED, NOT SECRET

Fig 4.5The accent bracket is what the signature covers: the first two parts and the dot between them, exactly as sent.

The signature is RSA-SHA256 over the text header.payload, exactly as sent: 359 characters. The sign-in server signs it with its private key, and the result is 256 bytes, 342 characters of base64url, about half the token.

Anyone can decode the first two parts. Nobody can change a character of them without the private key, because the signature would no longer match. A JWT is safe to show and unsafe to trust before you check it.

COMMON QUESTIONS

Is a session cookie a token too?
Yes, an opaque one: the print shop’s sid is 43 random characters it looks up in its own records. A JWT carries its meaning inside it.
Are all access tokens JWTs?
No. Google’s are opaque strings of up to 2,048 bytes that only Google can read, so an API has to ask about them (chapter 07).
Is it safe to paste a token into an online decoder?
The site receives a working credential. Decode it locally, as the sample does.

WHAT YOU NOW KNOW

  • The access token is three base64url parts: a 71-character header, a 287-character payload of 8 claims, and a 342-character signature.
  • Anyone holding it can read every claim with no key; nobody can change one without the sign-in server’s private key.
  • It names your account only by number, and says it is for the photo API for 300 seconds.
DEEP DIVE: four signing algorithms, encrypted JWTs and the JSON form

Four signing algorithms

The run’s bench.py signed the same claims four ways. RS256 makes a 658-character token, signs in 536 µs and verifies in 49.8 µs. ES256 (ECDSA on P-256) makes 402 characters and signs in 28.5 µs, and EdDSA on Ed25519 signs in 33.6 µs. HS256 makes 359 characters and verifies in 24.7 µs.

RSA is slowest to sign and the quickest of the public-key algorithms to verify.

Choosing one

RSA signs 19 times slower than ECDSA here and verifies faster, a good trade for a token signed once and checked on every API call. HS256 uses one secret shared by signer and verifier, so every API that can check such a token can also mint one.

Encrypted JWTs

JWE (RFC 7516) encrypts the payload so only the API can read it. The run’s sign-in server can issue them (the encrypt option in getResourceServerInfo), but this run doesn’t, and most deployments don’t either.

The JSON form, and “jot”

JWS, the signing format under JWT, also has a JSON serialization that can carry several signatures; tokens use the compact dotted form because it fits in a header. RFC 7519 suggests pronouncing JWT like the English word “jot”.

Checked without asking: the resource server

The print shop now sends the access token to the photo API, which has never seen it. The API keeps no list of tokens and doesn’t call the sign-in server for each request, so it must decide from the token alone whether it is real, unexpired and meant for it. How does the photo API trust a token without asking the server that issued it?

STEP 01 / 05

ONE HEADER CARRIES THE WHOLE CREDENTIAL

Fig 5.1The accent arrow is every API call from here on: one header, checked inside the photo API.

The print shop calls GET http://localhost:4000/photos with one header that matters: Authorization, the word Bearer, a space and the 702-character token, 709 characters in all (RFC 6750).

A bearer token works for whoever presents it: the API checks the token and nothing about the machine that sent it. The map adds the API’s token check, its cached key, and the sign-in server’s published key set.

STEP 02 / 05

ONE DOCUMENT, ONE KEY SET, FETCHED ONCE

Fig 5.2Follow 1 to 4: two requests and their replies, then the accent key checks every later token without another call.

The sign-in server publishes its metadata at /.well-known/openid-configuration: the discovery document, 1,443 bytes with 24 fields, among them authorization_endpoint, token_endpoint and jwks_uri. The print shop found /auth and /token there too.

The API then fetches /jwks, the JWKS: one RSA public key, kid photos-2026-11, with a 342-character modulus. It caches the key and checks every later token against the copy, with no further request to the sign-in server.

STEP 03 / 05

NINE CHECKS, IN ORDER

Fig 5.3Each row is one check the photo API runs on every token. A token for another API fails at the accent row.

check() runs nine checks and stops at the first failure: alg on the API’s own allow-list (RS256 only), typ, a known kid, the signature, iss, aud, exp, the required claims, and last scope.

The audience check compares aud with the API’s own address, http://localhost:4000. A token the same sign-in server issued for a different API has a perfect signature and still fails here. Remote MCP servers depend on the same check; the MCP tutorial shows a client asking for a token bound to one server.

A failed check answers 401 with WWW-Authenticate: Bearer error="invalid_token", which tells the client to get another token. A missing scope answers 403 insufficient_scope: the token is fine, and the permission isn’t in it.

THE PHOTO API’S CHECK, WITH PYJWT 2.15
import jwt

jwks = jwt.PyJWKClient("http://localhost:8080/jwks")  # fetched once, then cached

def check(access_token: str) -> dict:
    header = jwt.get_unverified_header(access_token)
    if header.get("typ") != "at+jwt":  # RFC 9068: refuse ID tokens and others
        raise jwt.InvalidTokenError("not an access token")
    key = jwks.get_signing_key_from_jwt(access_token)  # picks the key by 'kid'
    claims = jwt.decode(
        access_token,
        key.key,
        algorithms=["RS256"],  # an allow-list: 'none' and 'HS256' never pass
        issuer="http://localhost:8080",
        audience="http://localhost:4000",  # a token for another API fails here
        options={"require": ["exp", "iat", "sub", "aud", "iss", "jti"]},
    )
    if "photos:read" not in claims["scope"].split():
        raise PermissionError("insufficient_scope")  # answer 403, not 401
    return claims
STEP 04 / 05

THREE FORGERIES, THREE 401s

Fig 5.4Three forged tokens, one per card. The accent row in each is the check that refused it.

An attacker with a copy of the access token edits it three ways. Changing sub to 999999999999 and keeping the old signature gets 401 Signature verification failed. Setting alg to none and dropping the signature gets 401 alg none is not allowed. Setting it to HS256 and signing with the public key gets 401 alg HS256 is not allowed.

The last two are the bugs Tim McLean disclosed on 31 March 2015: several libraries took the algorithm from the token’s header. Told none, they skipped the signature; told HS256, they used the downloadable RSA public key as the HMAC secret (CVE-2015-9235). An allow-list in the API closes both.

STEP 05 / 05

NEW KEYS ARE PUBLISHED BEFORE THEY SIGN

Fig 5.5The key set over time. In the accent stretch both keys are published, and tokens signed by either one pass.

Every check above rests on one secret, the sign-in server’s private key. The kid header is what makes replacing it routine: the sign-in server publishes the new public key beside the old one, starts signing with the new one, and drops the old one once the last token it signed has expired, 300 seconds later here.

A production sign-in server keeps its private key in a key management service, which signs on request and never hands the key out; the KMS tutorial follows one such key.

COMMON QUESTIONS

401 or 403?
401 means this token is unacceptable and the client should get another. 403 with insufficient_scope means the token is fine and the permission isn’t in it, so a new token won’t help.
Does the API call the sign-in server on every request?
No. It fetches the key set once and calls again only for a kid it doesn’t know.
What if the API’s clock is off?
exp is compared with the API’s own clock. PyJWT’s leeway allows a few seconds of difference; this run uses 0, on one laptop’s clock.

WHAT YOU NOW KNOW

  • The photo API reads the discovery document and the key set once, then checks every token locally with the cached public key.
  • Each check runs nine tests in order, and the algorithm comes from the API’s own allow-list, never from the token.
  • All three forgeries got 401; the one secret that would beat every check is the sign-in server’s private key.
DEEP DIVE: Storm-0558, RFC 8725’s rules and psychic signatures

Storm-0558

In 2023 attackers Microsoft calls Storm-0558 used an acquired consumer signing key, which a validation bug let Exchange Online accept for enterprise accounts, to forge tokens and read mail (Microsoft, 14 July 2023). The US Cyber Safety Review Board counted 22 organizations affected. One signing key was worth more than every check on this page.

RFC 8725 (February 2020)

The JWT best-practice rules this chapter applies: verify against an allow-list of algorithms, never accept none by default, use an explicit typ, validate aud. Its update, draft-ietf-oauth-rfc8725bis-10 from August 2026, is in the RFC Editor queue.

Psychic signatures

CVE-2022-21449, published on 19 April 2022: Java 15 to 18 accepted an ECDSA signature with both of its values set to zero for any message and any key, so an ES256 JWT with an all-zero signature verified.

Refreshing keys safely

Cache the key set. On a token with an unknown kid, fetch it again, at most once every few minutes, and keep serving with the cached keys if the sign-in server is slow to answer.

Who signed in: OpenID Connect and the ID token

The access token lets the print shop read photos, and it says nothing the print shop may use about who is at the browser: it is addressed to the photo API and names your account only by number. Greeting you by name, and knowing it is you next time, needs a token addressed to the print shop itself. How does the print shop learn who signed in, and why can’t it use the access token for that?

STEP 01 / 04

THE WORD OPENID ADDS A SECOND TOKEN

Fig 6.1The accent token arrived in the same response as the access token, and only the print shop reads it.

OAuth grants access to an API; it never defined how to sign someone in. OpenID Connect adds that as a thin layer on top (Core 1.0, 25 February 2014; ISO/IEC 26131 since 2024). Put openid in the scope list, and the token endpoint also returns an ID token, a JWT addressed to the client.

The print shop asked for openid profile email, so its token response held a 670-character id_token. Most “Sign in with” buttons on the web run this same flow, with this same word in the scope list.

STEP 02 / 04

TWO TOKENS FROM ONE RESPONSE

Fig 6.2Both tokens, claim by claim. The accent row differs in kind: who each token is for.

Both are JWTs signed with the same key, photos-2026-11. The ID token carries your sub 248289761001, aud print-shop, a nonce, and, because you allowed profile and email, your name, Sam Rivera, and your email, sam@example.com.

Its aud is the print shop’s client id, not the photo API’s address, and its header has no typ. The print shop reads your name from it to greet you. The access token names only your account number and is addressed to the API.

STEP 03 / 04

THE NONCE TIES THE TOKEN TO THIS SIGN-IN

Fig 6.3The nonce leaves in the sign-in URL and returns inside the ID token. The accent check compares the two.

Before redirecting you, the print shop stored a random nonce, 22 characters, and put it in the sign-in URL. The sign-in server copies it into the ID token. An ID token copied from another sign-in carries a different nonce and is refused.

The sample checks the signature with the same key set, iss, aud print-shop, exp and the nonce. Then the print shop knows you as the pair of issuer and subject: (http://localhost:8080, 248289761001).

THE PRINT SHOP’S ID-TOKEN CHECK, WITH PYJWT 2.15
import jwt

jwks = jwt.PyJWKClient("http://localhost:8080/jwks")
key = jwks.get_signing_key_from_jwt(tokens["id_token"])
id_claims = jwt.decode(
    tokens["id_token"],
    key.key,
    algorithms=["RS256"],
    issuer="http://localhost:8080",
    audience="print-shop",  # addressed to the print shop, not to the photo API
)
if id_claims["nonce"] != session["nonce"]:  # this sign-in, not a replayed one
    raise jwt.InvalidTokenError("nonce mismatch")
user_id = (id_claims["iss"], id_claims["sub"])  # ('http://localhost:8080', '248289761001')
STEP 04 / 04

THE WRONG TOKEN AT THE RIGHT DOOR

Fig 6.4The photo API’s checks stop the ID token at the accent row; the aud row would have stopped it too.

Sent to the photo API as if it were an access token, the ID token has a valid signature, because the same key signed it. The API still answers 401 typ None is not an access token at the second check, and aud print-shop would have failed after it.

The rule runs both ways. The ID token is for the client and never goes to an API. The access token is for the API, and holding one proves nothing about who signed in.

COMMON QUESTIONS

Is “Sign in with Google” OAuth or OpenID Connect?
OpenID Connect: the same code flow with openid in the scopes and an ID token in the answer.
Where do more profile fields come from?
The userinfo endpoint, called with the access token. This run’s server puts the claims in the ID token instead, which saves a request.
Does signing out of the print shop sign me out of the photo service?
No. Chapter 08 shows the sign-in server’s own session, which outlives the app’s.

WHAT YOU NOW KNOW

  • Putting openid in the scopes made the token endpoint also return a 670-character ID token addressed to print-shop, with your name and email.
  • The print shop checks its signature, aud and nonce, and knows you by issuer and sub, not by email.
  • An ID token at the photo API gets 401: its missing typ and its aud both say it is for the print shop.
DEEP DIVE: userinfo, issuer and subject, and the ISO standards

Userinfo

OpenID Connect also defines a userinfo endpoint that returns the same profile claims in exchange for an access token. The run’s server puts them in the ID token instead (conformIdTokenClaims: false), which saves a request.

Issuer and subject

sub is unique only within one issuer, so an app that accepts several sign-in servers must key its accounts by the pair of iss and sub. Matching accounts by email across issuers lets anyone who can register an unverified email at one provider take over the matching account.

Standards status

In October 2024 the OpenID Foundation announced nine OpenID Connect specifications published as ISO/IEC 26131 to 26139:2024: Core, Discovery, Dynamic Client Registration, and the logout and session specifications.

Working without you: refresh tokens and revocation

You ordered 12 prints and closed the tab. The access token in the print shop’s session record works for 300 seconds, and the print shop’s worker starts downloading the originals after it has expired. It still needs no help from you, because the token response held a third string. When copies of these tokens leak, the photo service also needs a way to take them back. How does the print shop keep working without you, and what can the photo service take back?

STEP 01 / 05

THE REFRESH TOKEN GOES BACK TO ONE SERVER ONLY

Fig 7.1The accent arrow is the refresh token’s only trip: back to the server that issued it, never to the API.

A refresh token is a 43-character string the print shop sends only to /token, to get new access tokens without you. The sign-in server issued one because the print shop asked for offline_access and you allowed it. It lasts 14 days here.

The map lights the back channel again, adds the introspection and revocation endpoints, and lights the grant that every one of these tokens hangs from.

STEP 02 / 05

401, THEN ONE REFRESH, THEN 12 DOWNLOADS

Fig 7.2Follow 1 to 6. The accent pair is the refresh: one request to the sign-in server replaces the expired token.

The print shop’s worker asks for GET /photos/p001/original at 10:50:59, with the token whose exp is 10:50:57. The photo API compares it with its own clock and answers 401 with WWW-Authenticate: Bearer error="invalid_token", error_description="token expired".

The worker posts grant_type=refresh_token with its client secret and gets back a new 300-second access token and a new refresh token. It then downloads all 12 originals with 200, and your browser sends nothing.

THE PRINT SHOP’S REFRESH, AND WHAT 400 MEANS
import httpx


def refresh(session: dict) -> None:
    resp = httpx.post(
        "http://localhost:8080/token",
        auth=("print-shop", CLIENT_SECRET),
        data={"grant_type": "refresh_token", "refresh_token": session["refresh_token"]},
    )
    if resp.status_code == 400:  # {'error': 'invalid_grant'}: revoked or reused
        raise PermissionError("ask the user to sign in again")
    tokens = resp.json()
    session["access_token"] = tokens["access_token"]  # good for another 300 s
    session["refresh_token"] = tokens["refresh_token"]  # the old one is now spent
STEP 03 / 05

EVERY REFRESH TOKEN WORKS ONCE

Fig 7.3RT1 is used twice. The red ✗ on the replay revokes the grant, which is why the print shop’s RT2 fails after it.

The sign-in server uses token rotation: each refresh token works once and returns a replacement. The worker used RT1 and got RT2. An attacker then sends a copy of RT1. The server finds it already used, answers 400 invalid_grant and revokes the whole grant.

The print shop’s own RT2 now gets 400 invalid_grant too, and it has to send you through sign-in again. That cost is deliberate: a refresh token that arrives twice means two parties hold it, and the server can’t tell which one is the thief.

STEP 04 / 05

REVOKED, AND STILL ACCEPTED

Fig 7.4The bar is the stolen token’s 300 seconds. Both accent calls return your photos; the revocation sits between them.

The attacker also copied the current access token. Before the revocation it asks the photo API for your photo list and gets 200; after the grant is revoked it asks again and gets 200 again.

The photo API checks each JWT locally with its cached key, and nothing told it about the revocation. The stolen token still had 299.9 seconds to run. Revoking a grant stops new tokens; it can’t recall a JWT that is already signed and out.

STEP 05 / 05

THE SIGN-IN SERVER KEPT NO COPY

Fig 7.5Two kinds of access token. The accent row is when a revocation takes effect for each.

The API posts the stolen token to the sign-in server’s introspection endpoint (RFC 7662), which answers whether a token is still active. This server answers 400 unsupported_token_type, “Structured JWT Tokens cannot be introspected via the introspection_endpoint”: it never stored the JWT it signed.

That is the trade-off between the two kinds of access token. An opaque token is a random string the API must look up on every request, or cache, and a revocation takes effect at the next lookup. A JWT needs no lookup and stays valid until exp.

COMMON QUESTIONS

How long should an access token last?
Minutes, if it is a JWT. Defaults: Keycloak 5 minutes, Google 1 hour, Microsoft Entra ID 60–90 minutes, Auth0 24 hours.
How does a user disconnect an app?
The app calls the revocation endpoint (RFC 7009), which revokes the grant; the run’s server offers /token/revocation.
Why not give the API the refresh token?
Then every API could get new access tokens, and one leak would spread. Only the issuer accepts it.

WHAT YOU NOW KNOW

  • The 300-second token was refused at the first download, and one refresh let the worker download all 12 originals without you.
  • Each refresh token works once: a replayed copy revoked the grant, so the print shop’s newer token failed too.
  • The stolen access token still returned your photos after the revocation, because a JWT is checked locally and lasts until exp.
DEEP DIVE: revocation, real lifetimes and limits, two thefts, and faster than exp

Revoking on purpose

The revocation endpoint (RFC 7009, August 2013) takes a refresh or access token and answers 200 even for an unknown one, so nobody can use it to test whether a token exists. Revoking a refresh token usually revokes its grant; an app calls it when you disconnect it from your account.

Real lifetimes and limits

Microsoft Entra ID refresh tokens last 90 days, or 24 hours for single-page apps, and their lifetime has not been configurable since 30 January 2021. Google allows 100 refresh tokens per Google Account per OAuth client and invalidates the oldest, without an error, when a 101st is issued. Apps still in “Testing” status get refresh tokens that expire after 7 days.

Two thefts of OAuth tokens

In April 2022 GitHub found that OAuth user tokens issued to Heroku and Travis CI had been stolen and used to download private repositories from dozens of organizations, npm’s among them (GitHub, 15 April 2022). From 8 to 18 August 2025 an actor Google calls UNC6395 used OAuth tokens stolen from the Salesloft Drift integration to export data from customers’ Salesforce instances. All Drift tokens were revoked on 20 August 2025.

Faster than exp

Some providers push revocations to their APIs, as Microsoft’s Continuous Access Evaluation does, or let APIs keep a short denylist of jti values. Both add back a little shared state to recover what a pure JWT gives up: a way to stop one token before it expires.

Where tokens live: the backend for frontend

Every token so far is a bearer token, so wherever a copy can be read, it can be used. The print shop kept all three on its server, and your browser held only cookies. Many apps keep their tokens in the browser instead, where any script on the page can reach them. Where should a web app keep its tokens, and what does the browser hold instead?

STEP 01 / 04

THE BROWSER HOLDS TWO COOKIES AND NO TOKEN

Fig 8.1The accent chips are everything your browser holds: two cookies, each pointing at a record on a server.

Your browser holds two cookies. The print shop’s sid is 43 random characters, set with HttpOnly; SameSite=Lax; Path=/, and points to the session record where the three tokens are kept. The other is the sign-in server’s own session cookie.

Keeping every token on the app’s own server and giving the browser only a session cookie is the backend-for-frontend (BFF) pattern. RFC 10017, OAuth 2.0 for Browser-Based Applications (August 2026), lists it first and calls it the most secure of its options.

STEP 02 / 04

18 BROWSER REQUESTS, NO AUTHORIZATION HEADER

Fig 8.2One row per kind of browser request. The accent column, Authorization, is empty in every row.

In the whole run your browser sent 18 requests: both sign-ins, loading the photo page twice and placing the order. None of them carried an Authorization header.

To the print shop it sent sid; to the sign-in server, that server’s own cookies. Every request that carried a token came from the print shop’s server.

STEP 03 / 04

WHAT A SCRIPT ON THE PAGE CAN READ

Fig 8.3Each row is a place a browser app can keep a credential. The accent row is the one page scripts can’t read.

A single-page app often keeps its tokens in localStorage, sessionStorage or a JavaScript variable. Any script running on the page can read all three, so one XSS hole, a place where an attacker gets their own script into the page, copies every token out.

A cookie set with HttpOnly can’t be read by the page’s scripts at all; the browser only attaches it to requests. OWASP advises against keeping session identifiers in local storage.

STEP 04 / 04

ONE SIGN-IN COVERS EVERY APP

Fig 8.4The first sign-in on the left, the second on the right. The accent gap is the password form that didn’t appear.

Signing in again later, your browser sends 6 requests instead of 9 and sees no password form. The sign-in server’s session cookie still identified it, so it went straight to the Allow page, which appeared again only because the grant had been revoked.

That is single sign-on: one sign-in at the sign-in server covers every app that sends you there. It also means that signing out of the print shop leaves you signed in at the sign-in server.

COMMON QUESTIONS

Does a single-page app need a server for this?
Yes, a small one: the page calls its own backend, which holds the tokens and calls the API. RFC 10017 calls it the most secure option for browser apps.
Why SameSite=Lax rather than Strict?
The return from the sign-in server is a navigation from another site. With Strict the browser would drop sid on it, and the callback would lose its state and verifier.
Is the sign-in server’s cookie a token?
It is that server’s own session cookie, sent only to the sign-in server. No app ever sees it.

WHAT YOU NOW KNOW

  • The print shop kept all three tokens on its server behind a 43-character HttpOnly sid cookie, and none of your browser’s 18 requests carried a token.
  • Tokens in localStorage or a script variable are readable by every script on the page; an HttpOnly cookie isn’t.
  • The sign-in server’s own cookie made the second sign-in 6 requests with no password: single sign-on.
DEEP DIVE: the implicit flow, logging out, and a stolen session cookie

The implicit flow

OAuth 2.0’s implicit grant returned the access token in the URL fragment, for browser apps that had no server of their own to make a back-channel request. RFC 9700 says clients should not use it and the OAuth 2.1 draft omits it, yet this run’s sign-in server still lists implicit in grant_types_supported.

Logging out

OpenID Connect has RP-initiated logout (the run’s end_session_endpoint), front-channel logout and back-channel logout. Only the first is a link the app sends you to; the other two let the sign-in server tell every app you used that the session ended.

A stolen session cookie

The BFF moves the credential, it doesn’t remove it: whoever copies sid from the browser can act as you at the print shop. HttpOnly keeps it from page scripts, and the session record is the one place to expire it, which is why that record lives on the server.

A token bound to a key: DPoP

Keeping tokens on the server stops page scripts, but the server’s own copies can still leak: a log line, a backup, a breached integration. A copied bearer token got the attacker your photo list in chapter 07. The fix is to make the token worthless without a second thing that never leaves the print shop. How can a token be useless to whoever copies it?

STEP 01 / 04

A KEY PAIR THAT NEVER LEAVES THE PRINT SHOP

Fig 9.1The accent key never leaves the print shop’s server. Every accent call to the API now carries a proof made with it.

DPoP, Demonstrating Proof of Possession (RFC 9449, September 2023), binds a token to a key pair the client generates. The print shop makes an EC P-256 key pair and keeps the private half on its server.

Every request now carries a small proof signed with that private key. The map adds the key and changes what the photo API checks: the token and its proof.

STEP 02 / 04

THE TOKEN CARRIES A THUMBPRINT OF THE KEY

Fig 9.2Left, the proof sent to /token. Right, the token that came back. The accent line joins its thumbprint to the key.

With the code exchange, the print shop sends a DPoP proof whose header carries its public key. The sign-in server writes that key’s thumbprint, a SHA-256 hash of it, into the new access token as cnf.jkt, and answers token_type: DPoP.

The token grows from 702 to 782 characters. It is now sender-constrained: only the holder of the matching private key can use it.

STEP 03 / 04

ONE PROOF PER REQUEST

Fig 9.3The proof, decoded. The accent row ties it to one access token; the rows above tie it to one request.

Every API call carries a fresh proof in a DPoP header, 527 characters here: typ dpop+jwt, alg ES256 and the public key in its header; htm (the method), htu (the URL), iat, a unique jti and ath, a hash of the access token, in its claims.

The API checks the proof’s signature, that its key’s thumbprint matches the token’s cnf.jkt, and the method, URL and age. Listing your photos this way returns 200.

ONE PROOF PER REQUEST
import hashlib
import time
import uuid

import jwt
from cryptography.hazmat.primitives.asymmetric import ec

key = ec.generate_private_key(ec.SECP256R1())  # never leaves the print shop's server


def dpop_proof(method: str, url: str, access_token: str) -> str:
    claims = {
        "htm": method, "htu": url,  # good for this one request only
        "iat": int(time.time()), "jti": str(uuid.uuid4()),  # fresh, and never reused
        "ath": b64url(hashlib.sha256(access_token.encode()).digest()),  # and this token
    }
    header = {"typ": "dpop+jwt", "jwk": public_jwk(key)}  # the public half rides along
    return jwt.encode(claims, key, algorithm="ES256", headers=header)


url = "http://localhost:4000/photos"
headers = {"Authorization": f"DPoP {access_token}", "DPoP": dpop_proof("GET", url, access_token)}
STEP 04 / 04

THE SAME THEFT, TWO 401s

Fig 9.4Top, the chapter 07 theft. Below, the same theft of a DPoP-bound token; the accent row is the thumbprint mismatch.

The attacker copies the DPoP-bound token too. Sent as a bearer token, it gets 401, “token is DPoP-bound; Bearer not accepted”. Sent with a proof signed by the attacker’s own key, it gets 401, “proof key does not match the token”.

That proof is valid for its own key, but the key’s thumbprint isn’t the one in the token. The attacker has the token and not the key, which never left the print shop. In chapter 07 a copied bearer token returned your photo list.

COMMON QUESTIONS

DPoP or mutual TLS?
Mutual TLS (RFC 8705) binds a token to a client certificate and suits server-to-server calls; DPoP works where certificates are impractical, browsers included.
Can a browser app use DPoP?
Yes. It can create a non-extractable key with the Web Crypto API, so page scripts can sign with it and can’t copy it.
Does DPoP replace HTTPS?
No. It proves who holds the token; TLS still protects everything on the wire.

WHAT YOU NOW KNOW

  • The print shop’s P-256 key pair never leaves its server, and the token names that key by its thumbprint in cnf.jkt.
  • Every API call carries a 527-character proof tied to one method, one URL and one access token.
  • A stolen DPoP-bound token got 401 both ways it was tried, where the same theft of a bearer token returned your photos.
DEEP DIVE: certificate-bound tokens, devices without a keyboard, machine to machine, and bound refresh tokens

Certificate-bound tokens

RFC 8705 binds a token to the client’s TLS certificate instead of a DPoP key, putting the certificate’s thumbprint in cnf. It is common between servers and impractical in browsers.

Devices without a keyboard

The device authorization grant (RFC 8628, August 2019) shows a short code such as WDJB-MJHT and a URL; you approve on your phone while the device polls every 5 seconds. An 8-character code from the suggested 20-letter alphabet carries about 34.5 bits. The AWS access tutorial follows the AWS CLI’s version of it.

Machine to machine

The client credentials grant has no user at all: a service authenticates with its own secret or key and gets a token for itself. There is no consent page and no refresh token, because the service can simply ask again.

Binding refresh tokens

RFC 9449 also binds refresh tokens issued to public clients to the DPoP key, so a stolen refresh token from a browser or phone app is as useless as a stolen access token.

The whole picture

Here is every part from the nine chapters on one map, numbered to match the table below.

Each number matches a row of the table. The browser’s arrow signs you in; the print shop’s two fetch tokens and photos.
  1. 1browser

    carries you between the sites; holds cookies, never tokens

    lives in
    your laptop
    decides on
    nothing: it follows redirects
    when wrong
    a sign-in loop, or a callback without its session cookie
  2. 2print shop server (client)

    asks for scopes, swaps the code, calls the API

    lives in
    localhost:3000
    decides on
    which scopes to ask for; whether state and nonce match
    when wrong
    400 state mismatch; invalid_client at /token
  3. 3session record

    keeps the tokens on the server behind sid

    lives in
    the print shop’s server
    decides on
    which tokens belong to which browser
    when wrong
    tokens in localStorage, readable by any script on the page
  4. 4access token (JWT)

    lets the API serve one scope for 300 seconds

    lives in
    the session record
    decides on
    nothing: it is checked
    when wrong
    401 token expired; 403 insufficient_scope
  5. 5ID token

    tells the print shop who signed in

    lives in
    the session record
    decides on
    nothing: the print shop checks it
    when wrong
    nonce mismatch; 401 “typ None is not an access token” at an API
  6. 6refresh token

    gets new access tokens without you, once each

    lives in
    the session record
    decides on
    nothing: it goes only to /token
    when wrong
    400 invalid_grant: reused or revoked
  7. 7DPoP key pair

    binds tokens to a key that never leaves

    lives in
    the print shop’s server
    decides on
    signs one proof per request
    when wrong
    401 “proof key does not match the token”
  8. 8authorization endpoint /auth

    signs you in and asks for Allow

    lives in
    the sign-in server
    decides on
    exact redirect URI, your password, your consent
    when wrong
    a redirect URI error page; error=access_denied
  9. 9grant

    records what you allowed this client

    lives in
    the sign-in server
    decides on
    which tokens may be issued
    when wrong
    after it is revoked, every refresh gets invalid_grant
  10. 10token endpoint /token

    swaps a code or a refresh token for tokens

    lives in
    the sign-in server
    decides on
    client secret, code, PKCE verifier
    when wrong
    400 invalid_grant; 401 invalid_client
  11. 11signing key

    signs every JWT

    lives in
    the sign-in server (a KMS in production)
    decides on
    nothing: whoever holds it can mint tokens
    when wrong
    a leaked key means forged tokens every API accepts
  12. 12discovery document + JWKS

    publish every endpoint and the public keys

    lives in
    /.well-known/openid-configuration and /jwks
    decides on
    nothing: they are read
    when wrong
    no key for a token’s kid
  13. 13introspection + revocation

    answer “is it active?”; cancel a grant

    lives in
    the sign-in server
    decides on
    its own records
    when wrong
    unsupported_token_type for a JWT it never stored
  14. 14sign-in session

    keeps you signed in across apps

    lives in
    the sign-in server, through its own cookie
    decides on
    whether to show the password form again
    when wrong
    signing out of an app leaves you signed in
  15. 15photo API (resource server)

    checks each token locally, serves photos

    lives in
    localhost:4000
    decides on
    alg allow-list, signature, iss, aud, exp, scope
    when wrong
    401 invalid_token; 403 insufficient_scope
  16. ·authorization code

    a one-time, 60-second string through the browser

    lives in
    the callback URL
    decides on
    nothing: it is swapped
    when wrong
    invalid_grant after 60 seconds or a second use
  17. ·state and nonce

    tie the callback and the ID token to this sign-in

    lives in
    the print shop’s session
    decides on
    match or refuse
    when wrong
    400 state mismatch; nonce mismatch
  18. ·PKCE verifier and challenge

    prove the code’s holder started the sign-in

    lives in
    verifier on the print shop, challenge at the sign-in server
    decides on
    SHA-256 of the verifier equals the challenge
    when wrong
    invalid_grant
  19. ·sid cookie

    an HttpOnly pointer to the session record

    lives in
    the browser
    decides on
    nothing: it is sent
    when wrong
    the callback loses its session with SameSite=Strict

THREE THINGS TO KEEP

  • You approve in the browser, and the app’s server swaps a one-time code for tokens the browser never sees.
  • A JWT is signed, not secret. Anyone can read it, and the API can check it on its own.
  • A token works for whoever holds it, so keep tokens off the browser and bind them to a key.
HTTP/1.1 401 UnauthorizedWWW-Authenticate: Bearer error="invalid_token", error_description="tutorial expired"