Auth: API keys, OAuth 2.1, OIDC, JWTs, mTLS and agent-era auth

Reading: 42 min, plus 10 in closed details. Data as of October 2026; every flow recorded on 5 October 2026 against a lab authorization server, the official MCP Python SDK and two upstream APIs. Child of Topic: protocols.

The idea in one screen

Every request carries a credential that answers two questions, who is calling (authentication) and may they do this (authorization); good auth makes every copy of a credential worth as little as possible to whoever steals it: addressed to one audience, a few scopes, minutes of life, bound to a key where it matters, and never forwarded onward, only exchanged for a new one.

Fig. 1 · Each hop gets its own narrow token; the forwarded one is refused

  1. Token A, for one audience. The agent (an MCP client) runs the code flow with a PKCE verifier and resource = the MCP server, and receives token A: audience (aud) the MCP server, files:read, 300 s, plus a rotating refresh token (section 4).
  2. A opens one server. The agent calls a tool with Authorization: Bearer A; the MCP server checks signature, iss, aud, exp and scope before running it.
  3. Forwarding A is refused. If the MCP server passed A on to the mail API, the mail API would answer 401 "Audience doesn't match": A was never addressed to it (sections 8 and 9).
  4. Exchange A for B. The MCP server instead hands A to the authorization server with an assertion signed by its own key, and receives token B: audience the mail API, narrowed to mail:read, with an act claim naming the MCP server.
  5. B opens the mail API, and names both. The mail API accepts B under the same strict checks and sees alice, acted for by the MCP server: ready for policy and audit.
  6. A stolen copy is worth little. A thief who copies A from a log gets 300 s of files:read at one server, and nothing at the mail API. If A were bound to a key (DPoP or mTLS, section 7) the copy would be useless.

recorded in this page's lab (sections 4, 8 and 9 replay each arrow byte for byte): the lifetimes, scopes, audiences, the refusal text and the claims the mail API saw are the recorded ones.

You need HTTP headers and status codes (HTTP) and, for mTLS, the TLS handshake (TLS and certificates). The whole stack on one LLM request is Topic: protocols; this page owns credentials and delegation in depth. The running example: alice lets an agent (an MCP client) read her files through an MCP server, which needs her mail from a mail API; a batch job and a CI pipeline stand in for services with no user.

Principal, credential
who a request acts for (a person, a service, an agent for a person); the evidence it carries
Bearer, bound
accepted from whoever presents it, like cash; also needs proof of a private key or TLS connection the thief lacks
Audience, scope
which service a token is for (aud); what it allows there
Client, AS, RS
the app or agent acting; the authorization server that issues tokens; the resource server (API) that accepts them
Grant, PKCE
a way to obtain a token (authorization code, client credentials, device, refresh); proof that the client redeeming a code is the one that asked for it
ID token, JWT
a signed statement to an app about who logged in; a signed, self-contained token any holder of the public key can check
Token exchange
trading a token you received for a new one addressed to the next service
CredentialWhat it provesBound toLivesTypical use
API key"I hold the account's secret"nothing: whoever holds it is the accountuntil revokedyour backend calling an LLM provider
Session cookie"I logged in on this browser earlier"a server-side session recordhours to daysa web app's own users
OAuth access token"this user (or service) let this client do these things at this API"one audience, a few scopesminutesthird-party apps, CLIs, agents, MCP clients
Refresh token"I may get new access tokens without asking the user again"one client (and its key, if sender-constrained)days to months, rotatedstaying signed in
ID token (OIDC)"this person signed in, at this time, to this app"the app (its client_id)minutes"Sign in with Google": for the app, never for APIs
Client certificate (mTLS)"I hold this certificate's private key"the TLS connectionhours to a yearservice to service in a mesh
Signed request (SigV4)"I hold the secret, and I sent exactly this request now"this request, this region, this service, about five minutesone requestcalling AWS
DPoP-bound tokenan access token, plus "I hold the key it was issued to"a client key pairminuteshigh-value APIs, public clients

Not here: cookies and their attributes at the protocol level (HTTP, section 4); the TLS handshake, certificate chains and SPIFFE in the handshake (TLS and certificates); MCP's messages and transports (MCP); prompt injection, sandboxes and how an agent harness keeps secrets from the model (Agent security); SSH keys and certificates (SSH, section 4).

Status of the specs (checked 5 October 2026)
  • OAuth 2.1 is still an Internet-Draft: revision 16, 3 September 2026 (datatracker). It removes the implicit and password grants, requires PKCE (with one narrow exception), drops the PKCE "plain" method and requires exact redirect URI matching.
  • The security rules it consolidates are already an RFC: the OAuth 2.0 Security Best Current Practice, RFC 9700 (January 2025). Browser apps got their own BCP in August 2026: RFC 10017.
  • MCP's 2026-07-28 revision makes Client ID Metadata Documents the preferred way for a client to identify itself and deprecates dynamic client registration (MCP authorization, 2026-07-28). The spec cites the CIMD Internet-Draft at revision 00; the draft has since reached revision 02 (6 July 2026, datatracker). It cites OAuth 2.1 draft 13; the current draft is 16.
  • GitHub Actions OIDC tokens for repositories created after 15 July 2026 carry an immutable subject with owner and repository IDs (GitHub docs): cloud trust policies written against the old format do not match them (section 7).
Where and how this page measured (provenance)

Everything marked recorded was produced on 5 October 2026 by a lab built for this page: an OAuth 2.1 authorization server, an MCP server and client from the official Python SDK (mcp 2.3.0), and two upstream APIs (a mail API with strict and careless checks, a DPoP-protected notes API), all on one Apple M1 Pro laptop with Python 3.13.5, PyJWT 2.15.1 and cryptography 50.0.2, with a recording proxy in front of each server so every byte that crossed the wire was saved (scripts and raw output in this page's src/lab/, rerun with src/run_all.sh). Simulated: the browser and the user (a script fetched the authorization URL and the lab AS approved as alice, so no login or consent page appears); the client metadata host's certificate (a throwaway local CA). Real provider discovery documents were fetched read-only the same day. illustrative marks a picture of a shape, not data.

1. 401 or 403, and where a credential rides

The server first authenticates the credential (genuine, unexpired, meant for me?), then authorizes the action (may this principal read this file?). The two fail with different status codes, and the difference tells a client what to do next:

401 Unauthorized

Despite its name, unauthenticated: no credential, or one the server cannot accept (bad signature, expired, wrong audience). The server MUST say how to authenticate in a WWW-Authenticate header (RFC 9110 s15.5.2). A fresh credential can fix it.

403 Forbidden

The server knows who you are and the answer is no (RFC 9110 s15.5.4). A new token with the same rights will not help; more rights might. OAuth signals the scope case with error="insufficient_scope" (RFC 6750 s3.1).

A real 401 from the lab: a token minted for the mail API, presented to the MCP server. The header names the problem class and, in the MCP style, points to the document that says where to get a proper token (resource_metadata, section 9).


recorded For a request with no credential, RFC 6750 says the server "SHOULD NOT include an error code" (s3.1); the MCP SDK 2.3.0 server sends error="invalid_token" then too (the first step of the recorded flow on MCP, section 7), so a client cannot tell "no token" from "bad token" by the error code alone.

CarrierLooks likeExamples
A request headerAuthorization: Bearer eyJ..., x-api-key: ...OAuth tokens (RFC 6750 s2.1), LLM provider keys (Anthropic's SDKs moved the key from x-api-key to Authorization: Bearer in their October 2026 majors; the API accepts either, but a proxy that reads only one header breaks: migration guide)
A cookieCookie: __Host-sid=...browser sessions; the browser attaches it automatically, the convenience and the danger (section 3)
The TLS handshakea client certificate, below HTTPmTLS between services; the HTTP layer never sees a secret
A signature over the requestAuthorization: AWS4-HMAC-SHA256 Credential=..., Signature=...AWS SigV4; the secret itself never crosses the wire
The URL (avoid)?access_token=...forbidden for bearer tokens in OAuth 2.1 (draft-16 s10) and MCP: URLs end up in logs, browser history and Referer headers

Bearer against bound is the distinction that matters most. RFC 6750 defines a bearer token as one accepted from anyone who presents it (s1.2). API keys, session cookies and ordinary access tokens are all bearer credentials: a copy in a log file, a crash dump, a notebook or a model's context window is as good as the original. A sender-constrained credential also needs proof of a private key (a DPoP proof per request, or the TLS client certificate the token was issued to); section 7 shows a stolen bound token failing three ways.

Predict, then reveal

An agent's token has scope files:read. It calls write_file on an MCP server that checks scopes. Which status, and which header tells the client what to ask for?

Reveal
403 Forbidden with WWW-Authenticate: Bearer error="insufficient_scope", scope="files:write", resource_metadata="...". The token is genuine (so not 401); the fix is a step-up authorization that requests the union of the old and the new scopes (MCP Scope Challenge Handling). The parent page's Failure lab reproduces this case as "Missing scope: authenticated but not allowed".

2. API keys: the simplest credential, done properly

Your backend calls an LLM provider thousands of times a day, with no user to ask and no browser to redirect; the provider only needs to know which account to bill and limit. The root page's running request carries the answer in one header, x-api-key: sk-wirelab-not-a-real-key (a fake): a long random string the provider generated, showed you once and remembers. Whoever presents it is the account.

  • One key per service and environment. When staging's key leaks you revoke staging, and per-key usage tells you who spent what. Providers rate-limit per key or per organisation, so one runaway job on a shared key throttles everyone (429 with retry-after; the Failure lab case "429 Too Many Requests with Retry-After" shows the headers).
  • Store it in a secrets manager and inject it at run time: not in git, a notebook (outputs and cell history get shared), a Docker image layer, or a browser or mobile app (anyone can read it out). Redact Authorization and key headers at the logger: access logs, proxy debug logs and tracing spans are where bearer credentials most often leak.
  • Rotate with overlap. Create key 2, deploy it everywhere, watch key 1's usage fall to zero, then revoke key 1. Revoking first is an outage.
  • Show only a hint () in dashboards and logs, so people can tell keys apart.

What a key cannot do: it carries no user (every call is "the account"), no consent, no expiry unless you add one, and no audience narrower than the whole provider. Fine for your backend calling your provider; wrong once a third party (an app, an agent) acts for one of your users, which is what OAuth is for (section 4).

A good key says what it is, is unguessable, and can be rejected without a database lookup


recorded A lab key in the shape of GitHub's 2021 token redesign (GitHub blog, 5 April 2021). Prefix lab_: secret scanners (GitHub's, your CI's, your log pipeline's) match it with almost no false positives, and an underscore keeps double-click selection whole. Body: 30 characters from 62 symbols carry 30 × log2(62) = bits (GitHub quotes 178), so the server can store a plain SHA-256 of the key rather than the slow, salted hash a human-chosen password needs: there is nothing to brute-force. Checksum: the last six characters are a CRC32 of the body in base 62.

Predict, then reveal

A notebook that worked yesterday now gets 401 from the LLM provider on every call; your colleague's identical notebook works. The key in your environment variable has the right prefix. What do you check first?

Reveal
Which key the process actually sees, and whether it is still active: print its hint (prefix and last four characters), not the key, and compare with the provider's dashboard. Usual causes: a key revoked in a rotation, a staging key against the production endpoint, or a stale value cached by the kernel or a .env file loaded before the change. A 401 says "this key is not accepted"; a 403 would say "this key is fine but may not use this model or workspace".

3. Sessions against tokens: where the truth lives

HTTP forgets everything between requests, so after one password the site needs every later request to say "still me". The two answers differ in one thing: whether the server keeps the truth or hands it to the client.

The cookie. Set-Cookie: __Host-sid=...; Path=/; Secure; HttpOnly; SameSite=Lax: Secure keeps it off plain HTTP, HttpOnly hides it from page scripts, and SameSite=Lax keeps it off requests other sites trigger in the background, the main defence against CSRF (cross-site request forgery: a malicious page making your browser send a request to your bank, cookie included). The attributes, including the __Host- prefix that stops a sibling subdomain planting or overwriting the session cookie, are taught on HTTP (section 4).

Browser apps and OAuth. A single-page app that holds OAuth tokens in JavaScript exposes them to any injected script. The August 2026 BCP for browser apps, RFC 10017, describes three architectures and "strongly recommends" the BFF (right panel) for business apps, sensitive apps and apps handling personal data (s6.1); the pattern where the browser holds the tokens itself (s6.3) is "not recommended" for those apps.

A session ID points at the truth; a self-contained token is the truth; a BFF keeps tokens off the browser

Session: the cookie is a pointer

Log out, or "sign out everywhere", deletes the row: every copy of the cookie dies at once.

Self-contained token (JWT)

The API trusts the signed contents, so "log out" cannot reach a token already issued: it stays valid until exp (recorded in section 6).

Backend for frontend (BFF)

A small server-side component runs the OAuth flow and keeps the tokens; the browser holds only an HttpOnly cookie.

illustrative For a website's own users, server-side sessions remain the simpler and safer default; tokens earn their place when a third party, a mobile app or another service is involved.

Predict, then reveal

Your internal labelling tool stores a JWT in localStorage and sends it as a Bearer header. Someone proposes moving it to a cookie "for security". What do you gain, and what new risk appears?

Reveal
Gain: with HttpOnly, an injected script can no longer read the token and send it away (it can still act within the page while it runs). New risk: the browser now attaches the credential automatically, which opens CSRF; you need SameSite=Lax or Strict (and for state-changing requests, a CSRF token or a custom header check). RFC 10017's BFF pattern is this move done fully: tokens stay on a server, the browser holds only a session cookie.

4. OAuth 2.1: letting an app act for a user

alice wants a CLI agent to read her files on a cloud drive. Pasting her drive password into the agent would let it do everything she can, forever, indistinguishable from her. OAuth replaces the password with a delegation: the drive's login server asks alice once whether this app may do these things, and if she agrees gives the app a short-lived, limited token. The app never sees her password. Four roles, named in every spec (OAuth 2.1 draft-16 s1.1):

Resource owner

alice, whose data it is.

Client

The app or agent (a CLI, a web app, an MCP client). Public clients (CLIs, desktop and mobile apps, browser code) cannot keep a secret; confidential clients (servers) can.

Authorization server (AS)

Logs alice in, asks for consent, issues tokens: accounts.google.com, Microsoft Entra, Okta, Auth0, Keycloak, or your own.

Resource server (RS)

The API that holds the data and accepts the tokens: the drive API, an MCP server.

The authorization code flow with PKCE

The flow for anything a person logs into: web and mobile apps, CLIs, desktop agents, MCP clients. Predict first: an attacker can read the browser redirect (a malicious app that registered the same custom URL scheme on a phone, a browser extension, a log that records full URLs: the attacks of RFC 9700 s4.1 to s4.5). What does it end up holding in each mode? Then step through.

Fig. 2 · The same login three ways: only PKCE leaves the attacker with nothing it can redeem

  1. Verifier and challenge. The client first invents a random code_verifier (43 to 128 characters) and keeps it in memory; it will send only its SHA-256 hash, the challenge.
  2. Open /authorize ...code_challenge=E9Me... The authorization URL carries the challenge and code_challenge_method=S256; the AS stores the challenge with the code it is about to issue.
  3. alice logs in and approves. The user authenticates and consents.
  4. 302 /callback?code=...&iss=... The redirect carries the code (and, per RFC 9207, the AS's own name).
  5. The attacker reads the redirect and intercepts the code, exactly as before.
  6. POST /token code=..., no verifier. The attacker tries to redeem it. It has the code but not the verifier, and SHA-256 cannot be run backwards from the challenge.
  7. 400 invalid_grant. Refused. recorded from the lab AS: "invalid_grant: PKCE verification failed: S256(code_verifier) != code_challenge".
  8. The real callback. The real client receives the same redirect and checks state and iss.
  9. POST /token with the code and the verifier. If the attacker's attempt had already burned the code, the user logs in again: a denial, not a theft.
  10. 200: access and refresh token. Tokens go to the client over a direct TLS call; they never touched the browser. Same number of round trips as without PKCE: the price is one hash and two extra parameters.

The parameters you will debug in every authorization URL (a recorded one is in the flow on MCP, section 7):

  • response_type=code: ask for a one-time authorization code, not a token. The code comes back through the browser, the leaky part; the tokens come back on a direct, TLS-protected call from the client to the AS's token endpoint.
  • code_challenge, code_challenge_method=S256 (PKCE, RFC 7636): the client invents a random code_verifier, sends only its SHA-256 (base64url), and must present the verifier to redeem the code. The RFC's own example (verifier dBjftJeZ...EjXk gives challenge ) is recomputed live by this page's SHA-256: .
  • state: a random value the client checks on return, so an attacker cannot feed it a response to a request it never made (CSRF on the callback).
  • redirect_uri: must exactly match a registered value (RFC 9700 s4.1.3); pattern matching let attackers register lookalike paths and receive codes. For native apps on a loopback address the port may vary (RFC 8252 s7.3), which is how claude, gh and gcloud logins catch the redirect on http://127.0.0.1:<random port>/callback (the Failure lab's "OAuth redirect URI mismatch" shows a near-miss).
  • iss in the response (RFC 9207): the AS names itself, so a client talking to several authorization servers can refuse a response from the wrong one (a "mix-up" attack). MCP clients must check it; the SDK did, in the recording on MCP (section 7).
  • scope and resource: what the token may do, and for which API (RFC 8707). Together they decide how bad a leak is.

recorded Against the lab's authorization server: an interceptor who has the code but not the verifier, then a code used twice.


Correction to the old page
The old page said PKCE is "mandatory even for confidential clients". OAuth 2.1 draft-16 is one notch softer: PKCE is required unless the client is confidential and the AS has reasonable assurance it implements the OpenID Connect nonce correctly; even then PKCE stays recommended, because only PKCE lets the AS refuse an injected code before issuing any token (draft-16 s7.5.1.1). The draft also removed the redirect_uri parameter from the token request (s10.2); the MCP SDK 2.3.0 client still sends it (visible in the recording), and servers ignore it.

Refresh tokens: rotation catches a copy

Access tokens stay short (the lab's live 300 s) so a stolen one expires soon; a refresh token lets the client get new ones without sending alice through the browser again. Being long-lived, it is precious, so OAuth 2.1 requires that a public client's refresh tokens be sender-constrained (DPoP or mTLS) or rotated: each refresh returns a new refresh token and invalidates the old one, and if an old one is ever presented again someone has a copy, so the AS revokes the whole grant (draft-16 s4.3.1).

The thief's replay of a spent refresh token revokes the grant, logging out the real client too

recorded Statuses and error texts from the lab AS: "refresh token reuse detected; grant revoked", then "refresh token invalid or revoked". The AS cannot tell which of the two presenters was the thief, so both lose: one forced re-login against a silent, long-lived compromise. The same mechanism bites honest code: two processes sharing one refresh token look exactly like this (section 10).

Client credentials: a service acting as itself

With no user (a nightly batch job calling an internal API), the client authenticates as itself at the token endpoint and receives a token whose subject is the client. How it authenticates matters more than the grant: a shared secret in a Basic header (a secret to store and rotate), or better private_key_jwt, a short JWT assertion the client signs with its own private key and the AS checks with the registered public key (RFC 7523 s2.2), so no shared secret exists at all (the lab's MCP server authenticates this way in section 8). recorded with a secret:

The device grant: logging in a box with no browser

A GPU node over SSH, a TV, a CLI in a container cannot open a browser. The device asks the AS for a secret device code and a short user code, alice types the user code on her phone, and the device polls the token endpoint until she approves (RFC 8628). Polling rules: wait interval seconds (5 if unspecified); on slow_down, add 5 seconds for good (s3.5).

The user code is short on purpose: RFC 8628's own example, 8 characters from a 20-letter alphabet, carries 8 × log2(20) = bits, enough only because of rate limiting and expiry (s6.1). The flow's real weakness: the user approves a code someone else started. In the Storm-2372 campaign, attackers sent victims device codes disguised as meeting invitations, and the victims' approvals gave the attackers tokens; Microsoft's advice is to block the device flow wherever it is not needed (Microsoft Threat Intelligence, 13 February 2025).

The device polls; polling too fast earns slow_down; tokens arrive on the first poll after approval

recorded with the lab's interval set to 1 s to keep it short; after slow_down the AS answered "polling too fast; interval is now 6 s".

What OAuth 2.1 removed

OAuth 2.0 allowedOAuth 2.1 (draft-16 s10)Why
implicit grant (token in the redirect)removedtokens in URLs leak through history and referrers and cannot be sender-constrained
resource owner password grantremovedthe app saw the password
code flow without PKCE; PKCE plainPKCE by default, S256 onlyan intercepted code must be useless
redirect URI pattern matchingexact match (loopback port may vary)lookalike redirects received codes
bearer tokens in query stringsforbiddenURLs are logged
long-lived refresh tokens for public clientssender-constrained or one-time (rotated)a copy is detected or useless
redirect_uri in the token requestdropped; client credentials also accepted in the request bodysimplification

A draft is not a switch: "OAuth 2.1" in practice means your client uses only the 2.1 subset, whatever the provider still allows. Google's discovery document still advertises the implicit token response type and PKCE plain, for old clients.

What Google still offers, and two more pieces you will meet (discovery fields, PAR, AS metadata)

Google's discovery document, fetched for this page:

Pushed authorization requests (RFC 9126): the client posts the authorization parameters to the AS first and the browser carries only a reference, so nothing in the URL can be tampered with or leaked. Authorization server metadata (RFC 8414): the /.well-known/oauth-authorization-server document every client above read first.

Predict, then reveal

A mobile app uses the code flow with PKCE. A malicious app on the same phone registered the same custom URL scheme and receives the redirect, code included. What can it do with the code?

Reveal
Nothing useful: redeeming the code needs the code_verifier, which never left the real app's memory; the token endpoint answers invalid_grant (the recording above). Depending on the AS, its attempt may burn the code, so the user logs in again: a denial, not a theft. Without PKCE the same interception yields tokens, which is why RFC 8252 s6 required PKCE for native apps in 2017 and OAuth 2.1 extends it to everyone.

5. OpenID Connect: who logged in

OAuth answers "may this app call this API?" and deliberately says nothing about who the user is: an access token is addressed to the API, and the client is not even supposed to read it. Apps that wanted "Sign in with Google" abused access tokens as proof of identity, which is unsafe (a token issued to a different app could be replayed to yours). OpenID Connect adds the missing piece on top of the same code flow (OIDC Core 1.0):

  • Request scope openid and the token response also carries an ID token: a signed JWT about the login, addressed to your app (aud = your client_id), with iss, sub (a stable user ID, unique per issuer), exp, iat, auth_time and the nonce your app put in the authorization request (s2, s3.1.3.7).
  • A UserInfo endpoint returns profile claims (email, name) for an access token with the right scopes.
  • Discovery (OIDC Discovery 1.0): the provider describes itself at /.well-known/openid-configuration, including where its signing keys are (jwks_uri).

The rule people break: the ID token is for the app to learn who logged in. Never send it to an API as a credential, and never accept one as an access token. They look alike (both JWTs, often from the same issuer and key), which is why the JWT best practices ask for explicit typing (RFC 8725 s3.11); in section 6's validator, "An ID token, not an access token" passes signature, issuer and audience, and only the typ check stops it.

Same issuer, same key, same signature check: only typ (and the login fields) tell an ID token from an access token

recorded Two of the recorded tokens from section 6's validator, decoded; differing rows highlighted. The access token says typ: at+jwt (RFC 9068 s2.1); the ID token says JWT and carries nonce and auth_time. Here the client and the API share one identifier, so even aud matches.

Real discovery documents

Three providers, fetched read-only on ; each is a contract a client can check before it sends anyone a password.

  • Key rotation. Google signs ID tokens with RS256 and publishes keys at once, with cache-control: : two keys so it can sign with the new one while tokens signed with the old one are still valid, and a cache lifetime of hours so verifiers do not fetch keys per request. The verifier's rule: cache the JWKS, and when a token arrives with a kid you do not know, refetch once (rate-limited), never per request.
  • An issuer with no users. GitHub Actions mints ID tokens about workflow runs, with claims such as repository, ref and environment, which clouds trade for credentials (section 7).
  • An interoperability snag. Microsoft's common endpoint does not list code_challenge_methods_supported; Entra supports PKCE, but an MCP client following the 2026-07-28 rules literally must refuse to proceed when that field is absent (MCP authorization security, "Authorization Code Protection"). Visible only by reading the document.
Predict, then reveal

Your app validates the ID token's signature against Google's JWKS and checks exp. It does not check aud. What can an attacker who runs another site with "Sign in with Google" do?

Reveal
Log in to your app as any user who ever signed in to their site: they hold genuine Google ID tokens for those users, signed with the same keys, but with aud = their client_id. Without the audience check, your app accepts them. OIDC Core requires the client to verify that aud contains its own client_id (s3.1.3.7, rule 3), and the nonce check ties the token to your own login request.

6. JWTs: tokens a server can check alone

If every API call made the API ask the AS "is this token good?", the AS would carry the whole system's traffic and latency. A JSON Web Token puts the answer inside the token and signs it, so any API holding the AS's public key verifies it offline in microseconds (RFC 7519). The family, all May 2015: JWS (signed, RFC 7515), JWE (encrypted, RFC 7516), JWK (keys as JSON, RFC 7517), JWA (algorithm names, RFC 7518) and JWT (the claims). "JWT" in conversation almost always means a JWS-signed JWT.

Three base64url pieces: anyone can read the first two; only the signature needs a key

recorded An RS256 access token from the lab, decoded by this page's JavaScript: a header (algorithm and key ID), a payload (the claims) and a signature over the ASCII bytes base64url(header) + "." + base64url(payload). Base64url is an encoding, not encryption: put no secrets and no more personal data than needed in claims; use JWE or an opaque token if the contents must stay private.

The algorithms, measured

measured The same claims signed five ways with PyJWT 2.15.1 (Apple M1 Pro, one core; median of 7 runs of 200):

  • HS256 is a MAC with a shared secret: smallest and fastest, but every service that can verify can also mint tokens. Fine inside one service; wrong for an issuer with many verifiers.
  • RS256 is the most widely deployed (Google, Microsoft and GitHub Actions list only RS256 in the discovery documents of section 5). Verification is cheap and signing about ten times slower, which suits one issuer and many verifiers; its 256-byte signature makes tokens roughly twice the size of the others.
  • ES256 (P-256) and EdDSA (Ed25519) give 64-byte signatures. ECDSA needs care: Java 17.0.2 and 18 accepted an all-zero signature as valid for any message and any key, because the verifier skipped the check that r and s are at least 1 (CVE-2022-21449; Neil Madden, "Psychic signatures in Java", 19 April 2022).

Validating a JWT, in order

Fig. 3 · The recorded good token as three plates, checked in order by a verifier that chooses the algorithm and the key itself

  1. Three pieces. The token splits at its two dots into header, payload and signature, drawn to scale with their base64url lengths. Anyone can decode the first two; only the signature needs a key.
  2. Choose the algorithm yourself. Accept only the algorithm(s) you expect for this issuer; never let the token's alg header decide (RFC 8725 s3.1). In PyJWT that is algorithms=["RS256"], required since 2.0.0 (changelog); applications that passed "every algorithm" there were still open to key confusion until 2.4.0 (CVE-2022-29217).
  3. Choose the key yourself. Look the kid up in the issuer's JWKS, fetched from the jwks_uri in its discovery document and cached. Never fetch keys from a URL inside the token (jku, x5u); never treat kid as a file path or a database query.
  4. Verify the signature. RS256 over the ASCII bytes of header, dot, payload, with the key just chosen; for the recorded token the pinned verifier said "RS256 with the issuer's key: signature valid".
  5. Check the type (typ: at+jwt) so an ID token or another JWT from the same issuer is not accepted as an access token (RFC 8725 s3.11).
  6. Check iss equals the issuer you trust and aud contains your own identifier (s3.8, s3.9). Skipping aud "because it is our own issuer" is the classic bug: the same issuer mints tokens for every API you own, so a token for the least important one opens all of them.
  7. Check time: exp in the future, nbf/iat not in the future, with a small leeway (seconds to a couple of minutes) for clock skew.
  8. Only now authorize: scopes, roles, tenant, the specific object.

recorded The token is the lab's "A good token" (section 6's validator, below); its claims and the verdict are the recording's, checked with the clock at the recording time.

Twelve real tokens through a verifier you configure: predict which forgeries the "common bug" preset lets through, then click it

Presets:
Forgeries accepted
of 6 forged tokens
Bad tokens let through
of 11 that should fail

Verifier, step by step

recorded Made on 5 October 2026 by src/lab/jwt_cases.py with keys that existed only during the run, then run through two Python verifiers: pinned (RS256 only, key by kid from the issuer's own JWKS) and naive (does what the header says: accepts alg: none, HMAC with whatever key it finds, keys from kid file paths and jku URLs). The page replays those signature verdicts and computes the claim checks live, with the clock at the recording time. The root page's Failure lab shows five cases as a real gateway's 401 and 403 responses ("Expired JWT", "Wrong audience", "Clock skew: token not yet valid", "Algorithm confusion rejected", "Missing scope: authenticated but not allowed").

Weak HMAC secrets fall offline

One captured HS256 token lets an attacker test candidate secrets on their own machine, as fast as they can compute HMACs, with no rate limit. measured Plain Python on one core tried candidates in s ( per second) and found secret123. At that rate every 6-character secret of lowercase letters and digits takes 366 / rate = ; dedicated GPU crackers are faster still (not measured here). RFC 8725 s3.5 asks for keys with real entropy: use 32 random bytes, never a word. Integrity rests entirely on nobody else knowing the key, so a guessable secret is as bad as no signature.

Tamper with a token yourself (HS256 signed in your browser)

An HS256 token signed by this page's SHA-256 with the secret (shown on purpose: it is a demo). Add admin to scope and keep the signature: rejected; re-sign: accepted. The same token made by PyJWT in src/recompute.py is byte-identical: . (The weak token above was found in s of guessing.)

The price of offline checking: no early revocation

recorded A client-credentials token was revoked at the AS (RFC 7009); the AS's introspection endpoint (RFC 7662) then reported it inactive, and the MCP server, which validates JWTs offline, still accepted it:

The remedies, cheapest first: short lifetimes (minutes), so a revoked token dies soon anyway; a denylist of revoked jti values pushed to verifiers; introspection on every call for high-value operations, which brings the round trip back. Long-lived access tokens "to avoid refresh logic" turn a leak into an incident you cannot stop: keep minutes and add refresh. This is also why JWTs make poor browser sessions (section 3).

7. Beyond bearer: bound tokens, signed requests, cloud IAM and mTLS

Every credential so far is a bearer credential: steal it and you are the owner. Four designs make a stolen copy not enough.

DPoP: a token that only works with its key

The client generates a key pair and keeps the private key (RFC 9449, September 2023). With every request, to the token endpoint and to the API, it sends a DPoP header: a small JWT signed with that key. The AS puts the key's thumbprint (RFC 7638) into the token; the API checks that the proof was signed by that same key, for this request, just now.

Cost: one ES256 signature per request on the client (about µs here, from the table in section 6), one verification and a replay cache of recent jti values on the server. Not stopped: malware inside the client can ask it to sign proofs (RFC 9449 s11.4); the server-provided nonce (s8, s9) limits proofs made in advance. Use it for public clients holding valuable refresh tokens (OAuth 2.1 accepts it in place of rotation) and APIs where a token leaked into a log would be serious. The older alternative binds the token to a TLS client certificate (RFC 8705), natural where mTLS already exists.

The proof carries the public key; the token carries its thumbprint; they must match

Fields per RFC 9449 (s4.2 and s6.1); the URL is illustrative, the thumbprint recorded. The API checks: the proof's signature verifies with its jwk; thumbprint(jwk) equals the token's cnf.jkt; htm and htu match this request; iat is recent; jti was not seen before; ath is the hash of the presented token. Below, recorded: a token bound to the client's key, then stolen and refused three ways.

SigV4: AWS signs every request instead of sending a token

You hold an access key ID (public) and a secret access key (never sent). For each request the SDK builds a canonical request (method, path, sorted query, lowercased sorted headers, the signed-header list, the SHA-256 of the body), hashes it into a string to sign with the timestamp and a credential scope (date, region, service), derives a signing key by chaining HMACs of the secret over date, region, service and the literal aws4_request, and sends the final HMAC as the signature (AWS: create a signed request).

What this buys: the secret never crosses the wire, so a logged request leaks no reusable credential; the body hash stops anyone in the middle changing the request; the timestamp makes a captured request expire ("in most cases, a request must reach AWS within five minutes of the time stamp", AWS SigV4 overview). Cost: every client needs an SDK or these steps done exactly (header case, whitespace and URI encoding cause most SignatureDoesNotMatch errors), and clock skew beyond a few minutes breaks every call.

All four stages in this page's JavaScript: change one character and the whole signature changes


Defaults are the get-vanilla vector of the SigV4 test suite as shipped in botocore (example credentials AKIDEXAMPLE); they reproduce the suite's expected signature . Predict, then try: change the date by one day. The signing key changes too, which is why a leaked derived key is good for one day, one region, one service.

Cloud IAM and workload identity: no long-lived secrets at all

The best secret is one you never store. Code on an EC2 instance, a Lambda or a pod gets temporary credentials for its role from the platform (access key, secret and a session token sent as X-Amz-Security-Token), the SDK refreshes them before they expire, and IAM policies on the role decide what it may do: calling Bedrock, SageMaker or S3 from your own AWS code needs no key at all. Across clouds and from CI the same idea runs on OIDC:

Subject formatExample
Branch (format before 15 July 2026)repo:octo-org/octo-repo:ref:refs/heads/main
Environmentrepo:octo-org/octo-repo:environment:Production
Pull requestrepo:octo-org/octo-repo:pull_request
Immutable (repositories created after 15 July 2026; opt-in for older ones)repo:octo-org@123456/octo-repo@456789:ref:refs/heads/main

Two traps. A wildcard condition such as repo:octo-org/* lets every workflow on every branch of every repository in the organisation assume the role, so anyone who can push a branch anywhere holds its permissions: match the exact repository and a protected branch or environment. And a policy written for the old format silently stops matching new repositories, whose subject includes the numeric IDs; GitHub added them because a deleted organisation or repository name could be re-registered by someone else and inherit the old subject.

The CI job proves what it is with a signed ID token; the trust policy's match on sub is the whole security boundary

illustrative sequence; claim formats from GitHub's OIDC reference. A workflow with permissions: id-token: write gets a token from the issuer whose discovery document is in section 5; on AWS the trade is AssumeRoleWithWebIdentity.

mTLS: identity in the connection

With mutual TLS both sides present certificates in the handshake, so a service's identity is proven before any HTTP byte flows and there is no header to leak. Service meshes automate the hard part (issuing and rotating short-lived certificates per workload; SSH does the same for people and hosts with CA-signed short-lived SSH certificates, SSH section 4); SPIFFE standardises the identity as a URI such as spiffe://prod.example/ns/serving/sa/vllm inside the certificate (SPIFFE ID spec). Authorization then works on that name ("the gateway may call vLLM; the notebook may not"). The handshake, chains and failure modes are on TLS and certificates; the root's Failure lab has "mTLS: client certificate missing".

Fig. 4 · Both sides show a certificate; the name inside decides what the caller may do

  1. One private CA, short-lived certificates. The mesh's CA issues every workload its own certificate and private key, with the workload's SPIFFE ID inside, and rotates them automatically.
  2. The server shows its certificate. As in any TLS connection, vLLM presents its certificate and the gateway checks that it chains to the CA it trusts.
  3. The client shows one too. The gateway presents its own certificate and proves it holds the private key; vLLM checks the chain. Both identities are proven before any HTTP byte flows, and there is no header to leak.
  4. Authorization on the name. vLLM's policy reads the caller's SPIFFE ID: the gateway may call vLLM, so its request goes through.
  5. The notebook may not. A notebook with its own valid certificate completes the handshake but its name is not on the policy, so it is refused; a caller with no certificate at all fails in the handshake (the root's Failure lab case "mTLS: client certificate missing").

illustrative Structure only: the parties and the gateway's and notebook's IDs are examples in the SPIFFE format; nothing here was recorded. The handshake itself is taught on TLS and certificates.

Corrected from the old page
The old page said public CAs stop issuing client-authentication certificates in "February 2027". TLS and certificates (its section 7) checked the Chrome Root Program policy: leaf certificates issued from 15 March 2027 must carry only serverAuth. The advice is unchanged: use a private CA (or a mesh) for mTLS between your own services.
Predict, then reveal

A CI job's AWS calls work on GitHub-hosted runners but fail on one self-hosted runner with an error about the signature or the request time. Same code, same role. What do you check first?

Reveal
The runner's clock (date -u against a trusted time source). The timestamp is part of the string to sign and AWS refuses requests that arrive more than a few minutes away from it. After that, look for a proxy on that runner's network that rewrites a signed header (Host, Content-Type) or re-encodes the path, which changes the canonical request.

8. Token exchange: calling onward without forwarding

Service A received alice's token, addressed to A, and must call service B for her. Forwarding her token is wrong: B is not its audience, and if B accepts it anyway every token for A becomes a token for B. Using A's own all-powerful service credential is also wrong: B can no longer tell which user is behind the call, and A can be tricked into acting for the wrong user. The standard answer is token exchange (RFC 8693, January 2020): A authenticates to the AS as itself, hands over the token it received as the subject_token, names the target with resource or audience, and receives a new token for B, usually with narrower scopes.

Fig. 5 · Before and after on the same tool call: passthrough works only against a careless upstream, and hides the caller; exchange works against the careful one and names both

  1. tools/call inbox_passthrough. The client calls a tool with alice's token. Its audience is the MCP server: correct so far.
  2. GET /mail/inbox with the same token. The server forwards the token it received. This is token passthrough, which the MCP spec forbids.
  3. 401 "Audience doesn't match". A careful upstream checks aud and refuses: this token was never meant for it.
  4. Tool result: upstream 401. The tool fails. Passthrough only "works" against upstreams that skip the audience check, which is the next path.

recorded Three tool calls on one MCP connection, each needing alice's mail from the mail API; an arrow that carries a token is labelled with its audience. Predict what the careless upstream believes about the caller, then play it.

The recorded bytes of the current step (request and response)

In the exchange path the lab's MCP server authenticates with private_key_jwt (a JWT it signed with its own key, so no shared secret exists anywhere), and the AS's policy allows one mapping only: tokens for the MCP server, exchanged by the MCP server, for the mail API, scope narrowed to mail:read. The new token carries the distinction RFC 8693 names (s1.1). Delegation: "alice, acted for by the MCP server", with an act claim (s4.1), so the mail API can log and apply policy to both. Impersonation: simply "alice", and the API cannot tell an intermediary was involved. Prefer delegation whenever an agent or service acts for a person; the audit trail is the point.

The recorded exchange request and response (bytes)

Where you meet it. Microsoft Entra's equivalent is the on-behalf-of flow. In MCP, the enterprise-managed authorization extension (status: stable) chains two standard grants: the client exchanges the user's single-sign-on ID token at the company's identity provider for an ID-JAG (identity assertion JWT authorization grant), then presents it to the MCP server's AS as a JWT bearer grant (RFC 7523), so employees never click through a consent screen per server and administrators decide centrally which servers are allowed (MCP ext-auth; the underlying IETF draft is at revision 04, May 2026).

Predict, then reveal

In the recording, which three checks did the AS make before issuing the exchanged token, and which single one stops a compromised other service from using the MCP server's identity?

Reveal
It authenticated the caller (the private_key_jwt signature, issuer and audience, plus a one-time jti), validated the subject token (signature, issuer, and that its audience is the MCP server), and applied policy (only this client, only toward the mail API, scope narrowed). Client authentication is what stops another service: without the MCP server's private key it cannot produce the assertion, whatever tokens it has collected.

9. Agent-era auth: MCP authorization, audience binding, no token passthrough

An agent holds credentials and decides what to do with them from text it reads, some written by strangers (a web page, an email, a tool result). Auth cannot stop an agent being talked into misusing a credential it legitimately holds; that is the lethal trifecta and the harness's job (Agent security; Simon Willison named it, 16 June 2025). What auth can do is decide how much each credential is worth when that happens, and keep credentials from travelling further than intended. This section is MCP's authorization part, quoted from MCP 2026-07-28, Authorization and its sub-pages and checked against the official Python SDK; the protocol itself is on MCP.

MCP's authorization profile, seen from OAuth

Authorization is optional in MCP and applies to the HTTP transport; a local server started over stdio "SHOULD NOT follow this specification, and instead retrieve credentials from the environment". For a remote server MCP composes the pieces of sections 4 to 6 into one profile: a 401 whose WWW-Authenticate points to the server's protected resource metadata (RFC 9728), the authorization server's metadata (RFC 8414), a client identity without prior registration (a Client ID Metadata Document; dynamic client registration is now deprecated), PKCE S256, the resource parameter that binds the token to one server, an issuer check (RFC 9207) before the code goes anywhere, and Authorization: Bearer on every request, never the query string. The profile itself, recorded step by step with the official SDK (including the mix-up the SDK refused), is MCP's: MCP, section 7. Two of its OAuth rules apply beyond MCP: the client MUST refuse to proceed if the authorization server's metadata lacks code_challenge_methods_supported, and for public clients the AS MUST rotate refresh tokens. The rest of this section is the OAuth mechanics an MCP deployment depends on.

Audience binding: the server checks the token is for it

"MCP servers MUST validate that access tokens were issued specifically for them as the intended audience" and "MUST only accept tokens that are valid for use with their own resources." The client's half is the resource parameter, which asks the AS to put the server's URI in aud; the server's half is the 401 in section 1, a mail-API token refused by the MCP server.

A default worth knowing (MCP Python SDK 2.3.0)
The SDK's resource-server mode has a setting AuthSettings.validate_token_resource. In 2.3.0 it is off by default: with resource_server_url set and the setting left unset, the SDK warns that bearer tokens "are not checked against resource_server_url" and says the default becomes True in 3.0 (read from the installed package's mcp/server/auth/settings.py). Audience checking is then entirely up to your token verifier. The lab's server turns the setting on and passes the expected audience to PyJWT; do both.

No token passthrough

"MCP servers MUST NOT accept or transit any other tokens"; when a server calls an upstream API, "the access token used at the upstream API is a separate token, issued by the upstream authorization server. The MCP server MUST NOT pass through the token it received" (security considerations). Section 8's before/after is this rule recorded: a careless upstream accepts the forwarded token and believes alice's MCP client called it directly, so the MCP server, the actual caller, is invisible in its logs and to its per-client limits (the accountability failure the spec's best-practices page lists), and anyone holding a token for the MCP server reaches the mail API through it.

The three recorded tool calls, summarised (who the upstream believed was calling)

The confused deputy, MCP's version

An MCP server that fronts a third-party API with one static OAuth client ID is a deputy acting for many users. The spec's best-practices page walks through the attack (Confused Deputy Problem): alice once approved the proxy at the third-party AS, which set a consent cookie; an attacker registers a new client with the proxy (dynamic registration) using their own redirect URI and sends alice a link; the third-party AS sees the cookie, skips consent, and the code lands at the attacker. Required fixes on the proxy: per-client consent stored server-side before forwarding to the third party; a consent page that names the client, its scopes and its redirect URI; exact redirect matching; a state stored only after consent; consent cookies with the __Host- prefix, Secure, HttpOnly, SameSite=Lax and bound to the specific client_id.

Credential rules for agents

  • Out of the model's context. Anything in a prompt or tool result can be repeated into a tool call by an injected instruction, so tokens live in the client and server processes, attached by code to HTTP requests; how a harness enforces that is on Agent security (section 8, "the model cannot leak what it never sees").
  • Per user, per server. A server keeps upstream tokens per verified user, keyed by the token's sub, never by something the client sends. The same rule covers state handles in the stateless 2026-07-28 protocol: possession of a handle is not authentication; key stored state by <user_id>:<handle> with the user ID from the verified token ("State Handle Hijacking").
  • Better still, the agent never holds the secret. A broker keeps the credential and injects it outside the model's reach: 1Password for Agents (22 October 2026) has the agent ask for a login, a person approve it in 1Password, and 1Password fill the site's form, "so the agent never sees the password or one-time code" (1Password); NVIDIA's OpenShell runtime injects credentials only into requests to approved endpoints (OpenShell). What the agent can leak is then a request, not a key.
  • Short-lived, even on a laptop. The long-lived tokens that developer CLIs store are bearer credentials an agent on the same machine can read. In the October 2026 LiteLLM compromise a stolen GitHub CLI token let the attacker override branch protection and publish a backdoored release through the project's own pipeline (LiteLLM incident report); the same week GitHub's CLI added opt-in expiring tokens with a rotating refresh token (gh auth login --expiring), so "a leaked access token becomes unusable within hours instead of lasting indefinitely" (GitHub changelog). That is section 4's refresh-token rotation applied to a CLI.
  • Local servers get only their own secrets. A stdio server inherits environment variables from the host that starts it; give it only the variables it needs, not your whole shell environment.
  • Scopes small, then step up. Start read-only and let the server challenge with 403 insufficient_scope when a write is first attempted; the spec lists publishing every scope in scopes_supported, wildcard scopes and bundling unrelated privileges as common mistakes ("Scope Minimization"). Separate destructive scopes let the server enforce human approval of irreversible actions, which a host confirmation outside the conversation provides (Agent security, human approval).
  • Clients: server-supplied URLs are hostile. An authorization URL from a malicious server can be javascript: or carry shell metacharacters; clients MUST allow only http(s) (http only for loopback) and MUST NOT open URLs through a shell ("OAuth Authorization URL Validation").
Predict, then reveal

Your company runs one MCP server in front of the internal ticketing API. A teammate suggests: "the client already has the user's SSO token for ticketing, just let the MCP server forward it". List two things that break.

Reveal
(1) Audience binding: the MCP server would have to accept a token not issued for it, so any ticketing token (from any app) would work at the MCP server, and the MCP server would be a convenient proxy for stolen ones. (2) Accountability and control: the ticketing API sees the user's original client, not the MCP server, so it cannot rate-limit, scope or audit what the agent does separately. Correct design: the MCP server is a resource server with its own audience, and it obtains its own ticketing token by token exchange (or the enterprise-managed authorization extension), narrowed to what its tools need.

10. Choosing, and debugging

Which credential for which job

SituationUseAvoid
Your backend calls an LLM provideran API key per service and environment, from a secrets managerone shared key; keys in notebooks or images
Users sign in to your web appOIDC code flow with PKCE via a managed identity provider; server-side session or a BFFtokens in browser storage for sensitive apps
A CLI or desktop agent acts for a usercode flow with PKCE and a loopback redirect; device grant for headless boxesasking for the user's password; long-lived personal tokens
Service to service inside one cloudthe platform's workload identity (IAM roles); mTLS inside a meshstatic keys copied between services
Service to service across organisationsclient credentials with private_key_jwt or mTLS client authshared client secrets emailed around
CI deploying to a cloudOIDC federation with an exact subject conditioncloud keys stored as CI secrets
A remote MCP serverOAuth 2.1 per the MCP spec: CIMD, PKCE, resource, audience check; token exchange for upstreamstoken passthrough; one omnibus scope
A local MCP server (stdio)credentials from its own environment, only what it needsinheriting your whole shell environment

Debugging habits: always print the status and the WWW-Authenticate header (curl -sS -D - -o /dev/null ...); the server usually names the check that failed. Decode tokens to read them, but trust nothing they say about themselves until a signature check has run. Print key and token hints (first characters, last four, jti), never the values.

Symptom, first command, fix (twelve auth failures)
SymptomFirst commandUsual cause and fix
401, invalid_token, "expired" after the agent ran for a whiledecode the payload and compare exp with date -uno refresh logic; refresh before exp (minus a margin) or on the first 401, once.
401 "not yet valid" on one server onlydate -u on issuer and verifier; NTP statusclock skew; fix time sync, allow 30 to 120 s leeway.
401 "audience"decode aud; compare with the server's canonical URI (scheme, host, port, path, trailing slash)token requested without resource, or for another API; request it for this one. Never "fix" by disabling the check.
403 insufficient_scoperead the scope in WWW-Authenticate and in the tokenstep-up authorization requesting the union of old and new scopes.
Signature invalid after the provider rotated keyscompare the token's kid with the cached JWKSJWKS cached forever; refetch on unknown kid, rate-limited.
Browser login stops at the AS with a redirect_uri errorcopy the URL; diff its redirect_uri against the registered one character by characterport, trailing slash, http versus https, localhost versus 127.0.0.1; register the exact URI (loopback ports may vary).
invalid_grant at the token endpoint after the browser stepcheck that the verifier used is the one generated for this attempt; check the code was not already usedverifier lost across a process restart, or a retry reused the code; start a fresh authorization.
Refresh suddenly fails with invalid_grant for a user who did nothingAS logs for refresh-token reusetwo processes share one refresh token (both refresh, the second looks like theft and the grant is revoked); store tokens in one place and serialise refreshes.
Device login never completeslog each poll's error code and the interval usedpolling ignores slow_down, or the user approved a different code; honour the interval, show the full verification URL.
MCP client says the server "does not support PKCE"curl the AS metadata; look for code_challenge_methods_supportedthe AS omits the field (section 5); fix its metadata, or pre-register and configure the client.
AWS: signature or request-time errors on one machinedate -u; any proxy rewriting signed headersclock skew or header rewriting (section 7).
CI cannot assume the cloud role after a repository moveprint the OIDC token's sub in the job (it is not secret, but do not print the token)the subject format changed (immutable IDs); update the trust condition.
Interview rehearsal (eleven questions, model answers)
What is the difference between authentication and authorization, and how does HTTP show it?
Authentication establishes who the caller is; authorization decides whether that caller may perform this action. A failed or missing credential is 401 with a WWW-Authenticate challenge; a valid credential without permission is 403 (with OAuth, error="insufficient_scope").
Walk me through the authorization code flow with PKCE. What does PKCE protect against?
Client creates a random verifier and sends its S256 hash in the authorization request with state, redirect URI, scope and resource; the user authenticates and consents; the AS redirects back with a one-time code (and iss); the client checks state and iss, then redeems the code with the verifier at the token endpoint over a direct TLS call. PKCE stops an intercepted or injected code from being redeemed by anyone who does not hold the verifier, which matters most for public clients that have no secret.
Why did OAuth 2.1 remove the implicit grant?
It returned the access token in the redirect URL, where it leaks through history, referrers, extensions and logs, cannot be sender-constrained, and can be injected. The code flow with PKCE gives browser apps the same result with the token delivered on a back channel.
How would you validate a JWT access token?
Pin the expected algorithm; pick the key by kid from the issuer's cached JWKS (never from jku/x5u or a kid path); verify the signature; check typ (at+jwt), iss, aud (contains me), exp/nbf with small leeway; then authorize on scopes and the resource. Refetch JWKS on unknown kid, rate-limited.
JWT or opaque token with introspection? Trade-offs.
JWT: offline verification in microseconds, no AS on the hot path, but no early revocation and contents visible to anyone. Opaque with introspection: revocable immediately and private, but every call (or cache window) hits the AS. Common answer: short-lived JWTs plus refresh, with introspection or a denylist for high-value operations.
What is refresh token rotation and what does reuse detection buy you?
Each refresh returns a new refresh token and invalidates the old one. If an invalidated one is presented, two parties hold copies, so the AS revokes the whole grant: a stolen refresh token becomes detectable and short-lived, at the cost of logging the real user out too.
How do bearer tokens differ from DPoP or mTLS-bound tokens?
Bearer tokens work for whoever holds them. Bound tokens carry a confirmation (cnf) of a key; each request must prove possession (a signed DPoP proof covering method, URL, time and the token hash, or the TLS client certificate). A token stolen from a log is useless without the key.
Your service received a user's token and needs to call another service for them. What do you do?
Not forward it. Use token exchange (RFC 8693): authenticate as the service, present the received token as subject_token, request the downstream audience and narrower scopes, and prefer a delegation token with an act claim so the downstream sees both the user and the service.
How does a remote MCP server authorize clients, and what must the server check?
It is an OAuth resource server: 401 with resource_metadata, protected resource metadata naming its AS, the client discovers the AS, identifies itself (pre-registered, CIMD, or deprecated DCR), runs code + PKCE S256 with the resource parameter, checks iss, and sends Bearer tokens on every request. The server must validate each token including that its audience is this server, must not accept tokens for other resources, and must not pass tokens through to upstream APIs.
How do you give a CI job cloud access without storing a cloud secret?
Workload identity federation: the CI platform issues an OIDC token for the job; the cloud's token service exchanges it for short-lived credentials if a trust policy matches iss, aud and an exact sub (repository plus protected branch or environment). Watch for wildcards and for subject format changes.
Why is an API key acceptable for calling an LLM provider but not for a third-party integration?
Server to server under one owner, the key's lack of user context and consent does not matter, and secrets management plus rotation handle its risks. A third party acting for your users needs per-user consent, limited scopes, expiry and revocation per grant: OAuth.
Sources: every specific fact links its source inline. Recorded values come from this page's lab (src/lab/, rerun with src/run_all.sh), run on 5 October 2026 on an Apple M1 Pro with Python 3.13.5, PyJWT 2.15.1, cryptography 50.0.2 and the MCP Python SDK 2.3.0; the authorization server, upstream APIs and the browser and user are the lab's own (stated where they appear). Real provider documents were fetched read-only on the same day.