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
resource = the MCP server, and receives token A: audience (aud) the MCP server, files:read, 300 s, plus a rotating refresh token (section 4).Authorization: Bearer A; the MCP server checks signature, iss, aud, exp and scope before running it.mail:read, with an act claim naming the MCP server.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.
aud); what it allows there| Credential | What it proves | Bound to | Lives | Typical use |
|---|---|---|---|---|
| API key | "I hold the account's secret" | nothing: whoever holds it is the account | until revoked | your backend calling an LLM provider |
| Session cookie | "I logged in on this browser earlier" | a server-side session record | hours to days | a 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 scopes | minutes | third-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, rotated | staying 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 connection | hours to a year | service 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 minutes | one request | calling AWS |
| DPoP-bound token | an access token, plus "I hold the key it was issued to" | a client key pair | minutes | high-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).
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.
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:
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.
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.
| Carrier | Looks like | Examples |
|---|---|---|
| A request header | Authorization: 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 cookie | Cookie: __Host-sid=... | browser sessions; the browser attaches it automatically, the convenience and the danger (section 3) |
| The TLS handshake | a client certificate, below HTTP | mTLS between services; the HTTP layer never sees a secret |
| A signature over the request | Authorization: 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.
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?
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".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.
retry-after; the Failure lab case "429 Too Many Requests with Retry-After" shows the headers).Authorization and key headers at the logger: access logs, proxy debug logs and tracing spans are where bearer credentials most often leak.) 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).
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.
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?
.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".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.
Log out, or "sign out everywhere", deletes the row: every copy of the cookie dies at once.
The API trusts the signed contents, so "log out" cannot reach a token already issued: it stays valid until exp (recorded in section 6).
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.
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?
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.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):
alice, whose data it is.
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.
Logs alice in, asks for consent, issues tokens: accounts.google.com, Microsoft Entra, Okta, Auth0, Keycloak, or your own.
The API that holds the data and accepts the tokens: the drive API, an MCP server.
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
response_type=token. The client wants a token directly from the browser redirect (the OAuth 2.0 implicit grant, meant for browser apps that had no back end)./authorize. The client opens the browser at the authorization endpoint; the browser asks the AS. Nothing secret yet....#access_token=eyJ... The AS puts the access token itself in the redirect URL (in the fragment). It now sits in the browser: history, extensions, any script on the page./api with the token: 200. The attacker calls the API as alice. The token is a bearer token: no key, no binding, nothing more to steal. OAuth 2.1 removed this grant (draft-16 s10.1).response_type=code. The client asks for a one-time code instead of a token./authorize. The client opens the browser at the authorization endpoint; the browser asks the AS./callback?code=JTCl... The redirect carries only a code. Better: a code is single-use and short-lived. But it still passes through the browser./token code=JTCl... A public client (CLI, mobile app) has no secret, so nothing else is needed to redeem the code. The attacker redeems it first.code_verifier (43 to 128 characters) and keeps it in memory; it will send only its SHA-256 hash, the challenge./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./callback?code=...&iss=... The redirect carries the code (and, per RFC 9207, the AS's own name)./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.invalid_grant. Refused. recorded from the lab AS: "invalid_grant: PKCE verification failed: S256(code_verifier) != code_challenge".state and iss./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.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.
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.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).
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).
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:
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).
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".
| OAuth 2.0 allowed | OAuth 2.1 (draft-16 s10) | Why |
|---|---|---|
| implicit grant (token in the redirect) | removed | tokens in URLs leak through history and referrers and cannot be sender-constrained |
| resource owner password grant | removed | the app saw the password |
code flow without PKCE; PKCE plain | PKCE by default, S256 only | an intercepted code must be useless |
| redirect URI pattern matching | exact match (loopback port may vary) | lookalike redirects received codes |
| bearer tokens in query strings | forbidden | URLs are logged |
| long-lived refresh tokens for public clients | sender-constrained or one-time (rotated) | a copy is detected or useless |
redirect_uri in the token request | dropped; client credentials also accepted in the request body | simplification |
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.
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.
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?
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.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):
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)./.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.
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.
Three providers, fetched read-only on ; each is a contract a client can check before it sends anyone a password.
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.repository, ref and environment, which clouds trade for credentials (section 7).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.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?
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.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.
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.
measured The same claims signed five ways with PyJWT 2.15.1 (Apple M1 Pro, one core; median of 7 runs of 200):
Fig. 3 · The recorded good token as three plates, checked in order by a verifier that chooses the algorithm and the key itself
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).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.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).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.exp in the future, nbf/iat not in the future, with a small leeway (seconds to a couple of minutes) for clock skew.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.
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").
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.
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.)
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).
Every credential so far is a bearer credential: steal it and you are the owner. Four designs make a stolen copy not enough.
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.
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.
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.
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.
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 format | Example |
|---|---|
| Branch (format before 15 July 2026) | repo:octo-org/octo-repo:ref:refs/heads/main |
| Environment | repo:octo-org/octo-repo:environment:Production |
| Pull request | repo: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.
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.
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
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.
serverAuth. The advice is unchanged: use a private CA (or a mesh) for mTLS between your own services.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?
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.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
inbox_passthrough. The client calls a tool with alice's token. Its audience is the MCP server: correct so far./mail/inbox with the same token. The server forwards the token it received. This is token passthrough, which the MCP spec forbids.aud and refuses: this token was never meant for it.inbox_passthrough. Same call, but this time the upstream checks only the signature and expiry./mail/inbox with the same token. The forwarded token is genuine (same issuer, valid signature), just addressed to someone else.alice through client https://localhost:30613/client.json, with no act. The MCP server, which actually made the call, does not appear anywhere: no per-server limits, no audit trail, and any token for the MCP server now opens the mail API too.inbox_exchange. The client calls the tool with alice's token, audience the MCP server./token, a token exchange. The server authenticates to the AS as itself (private_key_jwt), hands over alice's token as subject_token, and asks for a token for the mail API (resource).mail:read, and act: {sub: mcp-files-server}./mail/inbox with the new token. The server calls the careful upstream with it.sub alice, client mcp-files-server and act {"sub": "mcp-files-server"}: both the user and the intermediary, ready for policy and audit.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.
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.
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).
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?
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.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.
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.
"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.
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."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.
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.
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").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.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).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").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.
| Situation | Use | Avoid |
|---|---|---|
| Your backend calls an LLM provider | an API key per service and environment, from a secrets manager | one shared key; keys in notebooks or images |
| Users sign in to your web app | OIDC code flow with PKCE via a managed identity provider; server-side session or a BFF | tokens in browser storage for sensitive apps |
| A CLI or desktop agent acts for a user | code flow with PKCE and a loopback redirect; device grant for headless boxes | asking for the user's password; long-lived personal tokens |
| Service to service inside one cloud | the platform's workload identity (IAM roles); mTLS inside a mesh | static keys copied between services |
| Service to service across organisations | client credentials with private_key_jwt or mTLS client auth | shared client secrets emailed around |
| CI deploying to a cloud | OIDC federation with an exact subject condition | cloud keys stored as CI secrets |
| A remote MCP server | OAuth 2.1 per the MCP spec: CIMD, PKCE, resource, audience check; token exchange for upstreams | token passthrough; one omnibus scope |
| A local MCP server (stdio) | credentials from its own environment, only what it needs | inheriting 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 | Usual cause and fix |
|---|---|---|
401, invalid_token, "expired" after the agent ran for a while | decode the payload and compare exp with date -u | no refresh logic; refresh before exp (minus a margin) or on the first 401, once. |
| 401 "not yet valid" on one server only | date -u on issuer and verifier; NTP status | clock 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_scope | read the scope in WWW-Authenticate and in the token | step-up authorization requesting the union of old and new scopes. |
| Signature invalid after the provider rotated keys | compare the token's kid with the cached JWKS | JWKS cached forever; refetch on unknown kid, rate-limited. |
Browser login stops at the AS with a redirect_uri error | copy the URL; diff its redirect_uri against the registered one character by character | port, 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 step | check that the verifier used is the one generated for this attempt; check the code was not already used | verifier 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 nothing | AS logs for refresh-token reuse | two 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 completes | log each poll's error code and the interval used | polling 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_supported | the AS omits the field (section 5); fix its metadata, or pre-register and configure the client. |
| AWS: signature or request-time errors on one machine | date -u; any proxy rewriting signed headers | clock skew or header rewriting (section 7). |
| CI cannot assume the cloud role after a repository move | print 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. |
WWW-Authenticate challenge; a valid credential without permission is 403 (with OAuth, error="insufficient_scope").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.Times are reading estimates: spec texts at about 200 words a minute, other pages from their length (core reading, as each page states it; dated October 2026).
The parent: one LLM request on the wire. its auth overview and agent protocols; the Failure lab's auth cases (expired, wrong audience, clock skew, algorithm confusion, missing scope, redirect mismatch, mTLS missing certificate).
The protocol this page's section 9 authorizes: messages, transports, the stateless revision, building and testing servers.
mTLS mechanics, certificate chains, workload identity (SPIFFE), what can go wrong in the handshake.
Headers, status codes and proxies, including how Authorization and WWW-Authenticate travel through them; cookies and their attributes (section 4).
The lethal trifecta, prompt injection, and how a harness keeps credentials out of the model's reach (section 8) and gates irreversible actions.
A2A's Agent Cards declare authentication schemes; the trust boundary for irreversible actions.
Keys, agents and SSH certificates: the other credential system on every cluster.
An MCP server and client built in TypeScript, every message recorded.
The hosts that hold an agent's credentials and decide what it may do.
API design around the auth layer: errors, idempotency, versioning.
The consolidated framework. Section 10 lists every change from 2.0; read it first.
Every attack behind the 2.1 rules, with countermeasures (section 4).
The JWT pitfalls list from the source; the checklist in section 6 follows it.
Discovery, client registration (CIMD), security considerations.
Confused deputy, token passthrough, SSRF, state handle hijacking, scope minimization.
ID tokens and their validation rules (section 3.1.3.7).
Sender-constrained tokens with per-request proofs.
Delegation and impersonation, the act claim.
How a resource server points clients to its authorization server.
BFF, token-mediating backend, browser clients: threats and recommendations.
Request signing as an alternative to bearer tokens.
Token claims, subject formats including the immutable one, cloud trust policies.
The clearest flow-by-flow walkthrough, by an editor of the OAuth 2.1 draft.
Index of every OAuth spec and extension with short explanations.
Why an agent with private data, untrusted input and an outbound channel leaks.
How an all-zero ECDSA signature verified as valid (CVE-2022-21449).
Prefixes, checksums and entropy for API keys.
The device grant used against its users, and the mitigations.