Be the OAuth and OIDC provider for MCP clients
For: an app developer whose users connect agents, MCP clients, services, devices, or other apps to the app.
What it does: core becomes an OAuth 2.1 authorization server and an OpenID Connect provider for public and confidential clients.
Before you start
Section titled “Before you start”- A working setup from a getting started tutorial.
jwtMinton. It is on by default. An access token is a JWT that core signs. JWT minting lists its keys.- Node 22.18 or newer for the tools of the project.
- Set
oauth.resourcesto the URLs of the resources that a client may ask for, 1 to 20. - Set
oauth.scopesto the scopes of your app, each with the text of the consent page. - Keep
registration.cimdoff.- To turn it on, pass
oauth.fetch, your own fetch that refuses private addresses. - Set
registration.dynamic: trueto servePOST /auth/oauth/register. It is off by default.
- To turn it on, pass
- Mount
auth.wellKnown(request)for every path that starts with/.well-known/at the origin root. - In each resource route, read the caller with
auth.caller(request).- Answer 401 to a caller that is not
kind: "oauth". - Answer
c.subjectto the client, neverc.user.id.c.subjectis the user id for a public client and the pairwise subject for a pairwise client.c.useris for the app.
- Answer 401 to a caller that is not
- Check the scope of each tool in the route. A token with only
openidmust not call a tool.
import { type Auth, createAuth, type MailPort, type StorageAdapter } from "@authtempo/core";import { readBearer, readSessionToken, sessionCookieNames } from "@authtempo/core/credentials";import { insufficientScopeResponse, unauthorizedResponse } from "@authtempo/verify";
export function createProviderAuth(deps: { storage: StorageAdapter; mail: MailPort; secret: string;}) { return createAuth({ baseURL: "https://api.example.com", trustedOrigins: [], secret: deps.secret, storage: deps.storage, mail: deps.mail, oauth: { // The resources that a client may ask for. Each is the `aud` of its access tokens. resources: ["https://api.example.com/mcp"], // The app's scopes, with the text of the consent page. scopes: { "mcp:tools": "Use your tools" }, // A client id may be the https URL of its metadata document. That needs // your own fetch, which refuses private addresses. This sample turns it off. // RFC 7591 registration is off by default. This sample turns it on. registration: { cimd: false, dynamic: true }, }, });}
const RESOURCE = "https://api.example.com/mcp";
/** * True when the request held a bearer and no session cookie. Core lets a * session cookie win and never reads the bearer then, so a refused cookie * request names no invalid_token (RFC 6750 section 3.1). The cookie names come * from core. */function refusedBearer(request: Request): boolean { if (readBearer(request) === null) return false; const headers = new Headers(request.headers); headers.delete("authorization"); return readSessionToken(sessionCookieNames(), { headers }) === null;}
/** The MCP resource: an access token for this resource, with the scope of the tools. */export async function mcpRoute(auth: Auth, request: Request): Promise<Response> { const c = await auth.caller(request); // The 401 names the scope that the route needs (MCP 2026-07-28). A bearer // that the route refuses adds error="invalid_token"; a cookie is no bearer. if (c?.kind !== "oauth") return unauthorizedResponse({ resource: RESOURCE, scope: "mcp:tools", invalidToken: refusedBearer(request), }); // Check the scope of each tool: a token with only openid must not call it. if (!c.scopes.includes("mcp:tools")) return insufficientScopeResponse({ resource: RESOURCE, scope: "mcp:tools" }); // c.user is for the app; c.subject is what the client may see. return Response.json({ sub: c.subject, clientId: c.clientId });}import type { Auth } from "@authtempo/core";import { DEFAULT_COOKIE_NAME } from "@authtempo/core/credentials";import { describe, expect, it } from "vitest";import { call, type Harness, harness, signIn } from "../support/harness.ts";import { createProviderAuth, mcpRoute } from "./oauth-provider.ts";
const API = "https://api.example.com";const REDIRECT = "http://127.0.0.1:8000/callback";
/** The code flow of a public client: register, authorize, allow, and exchange the code with PKCE. */async function accessToken(auth: Auth, h: Harness, scope: string): Promise<string> { const cookie = await signIn(auth, h, "ada@example.com"); const reg = await call(auth, "POST", "/auth/oauth/register", { client_name: "Agent", redirect_uris: [REDIRECT], }); const clientId = ((await reg.json()) as { client_id: string }).client_id; const verifier = Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString("base64url"); const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier)); const query = new URLSearchParams({ response_type: "code", client_id: clientId, redirect_uri: REDIRECT, code_challenge: Buffer.from(digest).toString("base64url"), code_challenge_method: "S256", scope, resource: `${API}/mcp`, state: "st-1", }); const consent = await call(auth, "GET", `/auth/oauth/authorize?${query}`, undefined, { cookie }); const requestId = /name="request_id" value="(oq_[A-Za-z0-9_-]+)"/.exec(await consent.text())?.[1] ?? ""; const allow = await auth.handle( new Request(`${API}/auth/oauth/authorize`, { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded", origin: API, cookie }, body: new URLSearchParams({ request_id: requestId, decision: "allow" }).toString(), }), ); const code = new URL(allow.headers.get("location") ?? `${API}/`).searchParams.get("code") ?? ""; const token = await auth.handle( new Request(`${API}/auth/oauth/token`, { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ grant_type: "authorization_code", code, code_verifier: verifier, client_id: clientId, redirect_uri: REDIRECT, resource: `${API}/mcp`, }).toString(), }), ); return ((await token.json()) as { access_token: string }).access_token;}
describe("be the OAuth and OIDC provider for MCP clients", () => { it("serves the metadata at the origin root and registers a public client", async () => { const auth = createProviderAuth(harness()); const server = (await ( await auth.wellKnown(new Request(`${API}/.well-known/oauth-authorization-server`)) ).json()) as { issuer: string; code_challenge_methods_supported: string[]; token_endpoint_auth_methods_supported: string[]; }; expect(server.issuer).toBe(`${API}/auth`); expect(server.code_challenge_methods_supported).toEqual(["S256"]); expect(server.token_endpoint_auth_methods_supported).toEqual([ "none", "client_secret_basic", "client_secret_post", "private_key_jwt", ]); const resource = (await ( await auth.wellKnown(new Request(`${API}/.well-known/oauth-protected-resource/mcp`)) ).json()) as { resource: string; }; expect(resource.resource).toBe(`${API}/mcp`);
const reg = await call(auth, "POST", "/auth/oauth/register", { client_name: "Agent", redirect_uris: ["http://127.0.0.1:8000/callback"], }); expect(reg.status).toBe(201); expect(((await reg.json()) as { client_id: string }).client_id.startsWith("cl_")).toBe(true); });
it("answers 401 with the resource metadata to a request with no access token", async () => { const res = await mcpRoute(createProviderAuth(harness()), new Request(`${API}/mcp`)); expect(res.status).toBe(401); expect(res.headers.get("www-authenticate")).toBe( 'Bearer resource_metadata="https://api.example.com/.well-known/oauth-protected-resource/mcp", scope="mcp:tools"', ); // A Basic header is no bearer: the plain challenge. const basic = await mcpRoute( createProviderAuth(harness()), new Request(`${API}/mcp`, { headers: { authorization: "Basic dXNlcjpwYXNz" } }), ); expect(basic.headers.get("www-authenticate")).toBe( 'Bearer resource_metadata="https://api.example.com/.well-known/oauth-protected-resource/mcp", scope="mcp:tools"', ); // With a session cookie, core reads the cookie and never the bearer: no error code. const withCookie = await mcpRoute( createProviderAuth(harness()), new Request(`${API}/mcp`, { headers: { cookie: `${DEFAULT_COOKIE_NAME}=ts_not_a_session`, authorization: "Bearer ts_not_a_token", }, }), ); expect(withCookie.headers.get("www-authenticate")).toBe( 'Bearer resource_metadata="https://api.example.com/.well-known/oauth-protected-resource/mcp", scope="mcp:tools"', ); // A bearer that the route refuses adds error="invalid_token" (RFC 6750 section 3.1). const refused = await mcpRoute( createProviderAuth(harness()), new Request(`${API}/mcp`, { headers: { authorization: "Bearer ts_not_a_token" } }), ); expect(refused.headers.get("www-authenticate")).toBe( 'Bearer error="invalid_token", resource_metadata="https://api.example.com/.well-known/oauth-protected-resource/mcp", scope="mcp:tools"', ); });
it("lets a token with the tools scope call the route, and answers 403 to a token without it", async () => { const h = harness(); const auth = createProviderAuth(h); const tools = await accessToken(auth, h, "mcp:tools"); const ok = await mcpRoute( auth, new Request(`${API}/mcp`, { headers: { authorization: `Bearer ${tools}` } }), ); expect(ok.status).toBe(200);
const openid = await accessToken(auth, h, "openid"); const refused = await mcpRoute( auth, new Request(`${API}/mcp`, { headers: { authorization: `Bearer ${openid}` } }), ); expect(refused.status).toBe(403); expect(refused.headers.get("www-authenticate")).toContain('error="insufficient_scope"'); });
it("lists the grants of the signed-in person for a connected apps page", async () => { const h = harness(); const auth = createProviderAuth(h); const ada = await signIn(auth, h, "ada@example.com"); const none = await call(auth, "GET", "/auth/oauth/grants", undefined, { cookie: ada }); expect(await none.json()).toEqual({ grants: [] });
await accessToken(auth, h, "mcp:tools"); const one = await call(auth, "GET", "/auth/oauth/grants", undefined, { cookie: ada }); const { grants } = (await one.json()) as { grants: Array<{ clientName: string; scopes: string[] }>; }; expect(grants.map((g) => [g.clientName, g.scopes])).toEqual([["Agent", ["mcp:tools"]]]); });});- Build a “connected apps” page with
client.oauth.grants()andclient.oauth.revoke({ clientId }).
How it behaves
Section titled “How it behaves”- A client of the registration is public unless it names a secret method or
private_key_jwt. A public client has no secret and sends PKCE S256 on every code. A redirect URI must match exactly. - A client registers at
POST /auth/oauth/registerwhileregistration.dynamicis on, or its client id is the https URL of its metadata document.api.oauth.clients.createmakes a client in your own code. The sweep deletes a client of the registration after 90 idle days, and keeps a client ofapi.oauth.clients.create. - A browser with no session goes to core’s sign-in page and comes back. An unverified user is refused.
- The sign-in page and the consent page carry
request_id, the id of a request that core holds for 10 minutes. The consent decides on the held request, not on the form. - A consent covers its scopes for every resource. A new scope asks again.
- An access token has
typ: "at+jwt",audthe resource, and livesaccessTtlMinutes. It passes only under its own resource, and nobody can revoke it. - A refresh token (
offline_access) rotates at each use. A client gets one only when itsgrant_typesholdrefresh_token, as the default list does. Without it, thescopeof the answer and of the access token leaves outoffline_access(2026-10-20). A used refresh token sent again deletes its whole family, unless the reuse window is on. - A password reset and a password change delete every refresh token, every pending code, and every decided device code of the user. The consents stay.
- A revoke under another client’s
client_idanswersunauthorized_clientand revokes nothing. - A browser client on another origin can call
/auth/oauth/tokenfrom a web origin of its own redirect URIs. That holds for a public client only. The answer carriesaccess-control-allow-originwith that origin and no credentials. Its form post to/auth/oauth/revoke, and itsPOST /auth/oauth/userinfowith no body, answer 403origin_not_trusted. Every other foreign origin also gets that 403 at/auth/oauth/token. A trusted origin gets credentialed CORS there. - The resource answers its 401 with
resource_metadataandscope, and its 403 witherror="insufficient_scope". The functionsunauthorizedResponseandinsufficientScopeResponseof the verify package write both. - The 401 names
error="invalid_token"only for a request with a bearer and no session cookie. Core reads a session cookie first and does not read the bearer then. - An authorize request with no
resourceanswersinvalid_target. Setoauth.defaultResourceto one entry ofoauth.resourcesfor a client that cannot sendresource. A namedresourcealways wins.
Confidential clients
Section titled “Confidential clients”A confidential client holds a credential. The token, revoke, and device routes take four client auth methods. The introspection route takes each method but none.
| Method | What the client sends |
|---|---|
none |
client_id alone. A public client. |
client_secret_basic |
HTTP Basic of the form-encoded id and secret. |
client_secret_post |
client_secret in the form. |
private_key_jwt |
A JWT client assertion of RFC 7523, signed by a key of its jwks or jwks_uri. |
- A client with a secret may send it by either secret method, one method per request (RFC 6749 section 2.3.1). Two methods answer
invalid_request. - A public client and a
private_key_jwtclient take their own method only. An emptyclient_secretcounts as omitted. - After an
Authorizationheader, a failed client auth answers 401invalid_clientwithWWW-Authenticate: Basic. With no header it answers 400 with no challenge, so a browser shows no sign-in dialog. - A failed client auth spends nothing. It counts on the per-IP key of its route. The token and revoke routes count
oauth-token:ip, introspectionoauth-introspect:ip, and the device startoauth-device:ip. A failed auth of a device poll also counts onoauth-token:ip, as on every other grant. No limit counts per client, so a stranger cannot lock a real client out. - A public client sends PKCE S256 on every code. A confidential client may omit PKCE only when it asks
openidwith a non-emptynonce(RFC 9700 section 2.1.1). - The assertion of
private_key_jwthas the client id asissandsub, and the issuer alone asaud. The token endpoint URL asaudis refused (draft-ietf-oauth-rfc7523bis-11). - An assertion lives at most 300 seconds, with 30 seconds of skew. Its
jtiworks once. The algs are EdDSA, Ed25519, ES256, RS256, and PS256. - A registration that omits
token_endpoint_auth_methodgetsnone, not theclient_secret_basicof RFC 7591. An MCP client that omits the field works as a public client. - A registration of a secret method answers
client_secret(cs_and 32 random bytes) andclient_secret_expires_at: 0once. Core stores the SHA-256 of the secret only.
api.oauth.clients makes clients in your own code. No route answers it. It has six calls:
createmakes a client of kindapi. It answers the secret of a secret client once. The 90-day idle sweep keeps the client: an operator made it on purpose.get,list,update, anddelete.listanswers newest first, 100 per page, with a cursor.updatechanges every field but the id, the method, and the secret.deleteremoves the client with its consents, refresh tokens, device grants, session links, and pending sign-out posts.rotateSecretanswers a new secret. The old one passes forkeepOldHoursmore, 0 to 168, 24 by default.- Each call answers an OAuth result. An unknown id answers
invalid_client. - Only
createandupdatetakeclient_credentials,credentialsScopes, andintrospect.
A service that acts for no person uses the client_credentials grant:
- Its client is confidential, and its
grantTypeshold the grant. A public client, or a client without the grant, answersunauthorized_client. - A scope of the grant must be in both
credentialsScopesandoauth.scopes. With noscope, the token gets every scope in both. - The answer holds no refresh token and no ID token.
auth.calleranswers the token askind: "oauth-client", with no user. - The token passes only while its client exists and holds the grant. A delete or an update of the client ends it at once.
oauth-token:ipcounts each request first, so a service on one IP gets 60 tokens per 15 minutes (limits). Keep the token until itsexpires_inends.
import { type Auth, createAuth, DEVICE_GRANT, type MailPort, type StorageAdapter,} from "@authtempo/core";
export function createClientsAuth(deps: { storage: StorageAdapter; mail: MailPort; secret: string;}) { return createAuth({ baseURL: "https://api.example.com", trustedOrigins: [], secret: deps.secret, storage: deps.storage, mail: deps.mail, oauth: { resources: ["https://api.example.com/mcp"], scopes: { "mcp:tools": "Use your tools", "reports:read": "Read your reports" }, // This sample makes its clients in code, so no client registers itself. registration: { cimd: false, dynamic: false }, // The device grant of RFC 8628 is off by default. {} turns it on with a // 10-minute code and a 5-second poll interval. device: {}, }, });}
/** The client API exists only while the config sets `oauth`. */function clientsOf(auth: Auth) { if (!auth.api.oauth) throw new Error("the config sets no oauth"); return auth.api.oauth.clients;}
/** * A service that acts for no person: the client_credentials grant. Only * api.oauth.clients gives this grant; a registration never does. */export async function createServiceClient(auth: Auth) { const made = await clientsOf(auth).create({ name: "Report service", authMethod: "client_secret_basic", grantTypes: ["client_credentials"], // The app scopes that the service may ask for. A built-in scope names a person, so it is refused. credentialsScopes: ["reports:read"], }); if (!made.ok) throw new Error(`the client create answered ${made.error}`); // The secret leaves core once, here. Keep it in the secret store of the service. return { clientId: made.value.client.id, clientSecret: made.value.clientSecret ?? "" };}
/** A device with no browser, such as a TV or a CLI: a public client of the device grant. */export async function createDeviceClient(auth: Auth): Promise<string> { const made = await clientsOf(auth).create({ name: "Living room TV", authMethod: "none", grantTypes: [DEVICE_GRANT], }); if (!made.ok) throw new Error(`the client create answered ${made.error}`); return made.value.client.id;}import { describe, expect, it } from "vitest";import { call, harness, signIn } from "../support/harness.ts";import { createClientsAuth, createDeviceClient, createServiceClient } from "./oauth-clients.ts";
const API = "https://api.example.com";const RESOURCE = `${API}/mcp`;
/** A form post to a provider route, with no Origin header: a server or a device. */function form(path: string, fields: Record<string, string>, headers: Record<string, string> = {}) { return new Request(`${API}${path}`, { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded", ...headers }, body: new URLSearchParams(fields).toString(), });}
describe("serve services and devices with the OAuth provider", () => { it("gives a service a token for no person with the client_credentials grant", async () => { const auth = createClientsAuth(harness()); const { clientId, clientSecret } = await createServiceClient(auth); expect(clientSecret.startsWith("cs_")).toBe(true); // client_secret_basic: HTTP Basic of the form-encoded id and secret (RFC 6749 section 2.3.1). const basic = btoa(`${encodeURIComponent(clientId)}:${encodeURIComponent(clientSecret)}`); const res = await auth.handle( form( "/auth/oauth/token", { grant_type: "client_credentials", resource: RESOURCE, scope: "reports:read" }, { authorization: `Basic ${basic}` }, ), ); expect(res.status).toBe(200); const token = (await res.json()) as Record<string, unknown>; expect(token.token_type).toBe("Bearer"); expect(token.scope).toBe("reports:read"); expect(token.refresh_token).toBeUndefined();
const caller = await auth.caller( new Request(RESOURCE, { headers: { authorization: `Bearer ${String(token.access_token)}` } }), ); expect(caller?.kind).toBe("oauth-client"); expect(caller?.kind === "oauth-client" ? caller.clientId : null).toBe(clientId);
// A wrong secret after an Authorization header: 401 with the Basic challenge. const wrong = btoa(`${encodeURIComponent(clientId)}:cs_wrong`); const refused = await auth.handle( form( "/auth/oauth/token", { grant_type: "client_credentials", resource: RESOURCE }, { authorization: `Basic ${wrong}` }, ), ); expect(refused.status).toBe(401); expect(await refused.json()).toEqual({ error: "invalid_client" }); expect(refused.headers.get("www-authenticate")).toBe(`Basic realm="${API}/auth"`); });
it("lets a person approve a device code, and the device polls once for its tokens", async () => { const h = harness(); const auth = createClientsAuth(h); const clientId = await createDeviceClient(auth);
const start = await auth.handle( form("/auth/oauth/device_authorization", { client_id: clientId, scope: "mcp:tools", resource: RESOURCE, }), ); expect(start.status).toBe(200); const device = (await start.json()) as { device_code: string; user_code: string; verification_uri: string; interval: number; }; expect(device.verification_uri).toBe(`${API}/auth/oauth/device`); expect(device.user_code).toMatch(/^[BCDFGHJKLMNPQRSTVWXZ]{4}-[BCDFGHJKLMNPQRSTVWXZ]{4}$/); expect(device.interval).toBe(5);
// The person signs in on a phone or a laptop and types the code on the device page. const cookie = await signIn(auth, h, "ada@example.com"); const page = { cookie, origin: API }; const consent = await auth.handle( form("/auth/oauth/device", { user_code: device.user_code }, page), ); expect(await consent.text()).toContain("Approve only a device that is in front of you."); const allow = await auth.handle( form("/auth/oauth/device", { user_code: device.user_code, decision: "allow" }, page), ); expect(allow.status).toBe(200);
const poll = { grant_type: DEVICE_URN, device_code: device.device_code, client_id: clientId }; const tokens = await auth.handle(form("/auth/oauth/token", poll)); expect(tokens.status).toBe(200); expect(((await tokens.json()) as { scope: string }).scope).toBe("mcp:tools"); // An approved code gives its tokens once. const again = await auth.handle(form("/auth/oauth/token", poll)); expect(await again.json()).toEqual({ error: "invalid_grant" }); });
it("refuses a device poll before the person decides", async () => { const auth = createClientsAuth(harness()); const clientId = await createDeviceClient(auth); const start = await auth.handle( form("/auth/oauth/device_authorization", { client_id: clientId, scope: "mcp:tools", resource: RESOURCE, }), ); const { device_code } = (await start.json()) as { device_code: string }; const poll = await auth.handle( form("/auth/oauth/token", { grant_type: DEVICE_URN, device_code, client_id: clientId }), ); expect(poll.status).toBe(400); expect(await poll.json()).toEqual({ error: "authorization_pending" }); // The page route exists only while oauth.device is on; a signed-out browser goes to the sign-in step. const signedOut = await call(auth, "GET", "/auth/oauth/device"); expect(signedOut.status).toBe(302); });});
/** RFC 8628 section 3.4. Typed here, so the test does not read the constant it checks. */const DEVICE_URN = "urn:ietf:params:oauth:grant-type:device_code";Client metadata documents
Section titled “Client metadata documents”With registration.cimd on, a client id may be the https URL of its metadata document. Core implements draft-ietf-oauth-client-id-metadata-document-02. It accepts the documents of -00, which MCP 2026-07-28 pins.
- Core fetches the document through
oauth.fetch, withredirect: "manual", 10 seconds, and 8 KB at most. It keeps the document one hour per isolate. - The document’s
client_idmust equal its URL. - A document with
client_secretorclient_secret_expires_atis refused (-02 section 4.1). So is a method other thannoneorprivate_key_jwt. - A
private_key_jwtdocument withjwksorjwks_uriis a confidential client. It signs a client assertion at the token route. - A document cannot change at the request of this server. So core drops each member that it does not serve, and writes a warning with the member name.
- Core drops each entry of
grant_typesorresponse_typesthat it does not serve, and anid_token_signed_response_algother thanjwtMint.alg. - A pairwise document loses
sector_identifier_uriand the device grant of itsgrant_types. - Core drops a
backchannel_logout_urithat is not valid, is off the host of the document, or has nooauth.fetchto post to it. It also drops abackchannel_logout_session_requiredthat is not a boolean. - A document with no
authorization_codegrant or nocoderesponse type is refused. - When a document changes from
private_key_jwttonone, core revokes every refresh token and deletes every device code of the client in the same write.
The device flow
Section titled “The device flow”The device grant of RFC 8628 serves a device with no browser, such as a TV or a CLI. Set oauth.device: {} to turn it on.
- Give a client the grant
urn:ietf:params:oauth:grant-type:device_code. - The device posts to
POST /auth/oauth/device_authorizationwith its client auth,scope, andresource. - The device shows
user_codeandverification_urito the person. - The person opens
GET /auth/oauth/device, signs in, and types the code. - The page shows the client, the scopes, and the line “Approve only a device that is in front of you.”
- The device polls
/auth/oauth/tokenwithdevice_code, everyintervalseconds.
- The user code is
XXXX-XXXXof the lettersBCDFGHJKLMNPQRSTVWXZ. It livesoauth.device.codeTtlMinutes, 10 minutes by default. verification_uri_completefills the field. The person still submits it.- A poll before the decision answers
authorization_pending. A poll withinintervalseconds answersslow_down, and the interval grows by 5 seconds. - A poll of a known code by the client of the code counts on its own key, not on
oauth-token:ip. So a device can poll at its interval for the whole code life (limits). A poll under another client id counts onoauth-token:ip. - A deny answers
access_denied, and an expired codeexpired_token. An approved code gives its tokens once, theninvalid_grant. - Only the client that asked may poll. A DPoP proof at the device request binds the code to its key.
- Core stores a SHA-256 of the device code and an HMAC of the user code under the app secret, never a code.
- With
oauth.signInURL, the person types the code again after the sign-in. Core never stores a user code in clear. - A pairwise client cannot take the grant. It has no redirect that ties a sector to the client.
- A reset, a password change, and a grant revoke delete the device codes that the user decided.
The device page counts each post: 5 per session and 20 per IP per 15 minutes. Each window opens at its first call, so one code life can meet two windows. A 10-minute code then takes at most 9 guesses per session and 39 per IP. A custom limiter with windows on the clock allows 10 and 40. Limits gives the odds.
DPoP of RFC 9449 binds a token to a key of the client. A copy of a bound token is useless without the key.
- The client sends a
DPoPheader with a proof on a grant at/auth/oauth/token. The access token then holdscnf.jkt, andtoken_typeisDPoP. - A public client’s refresh token is bound to the key too. A confidential client’s refresh token stays unbound (RFC 9449 section 5).
dpop_jktat the authorize step binds the code to a key. The exchange then needs a proof of that key.- A client of
dpop_bound_access_tokensmust send a proof on every grant. - A resource gets
Authorization: DPoP <token>and a proof for its URL and method.auth.callerchecks the proof, andc.dpopJktholds the thumbprint. auth.callerspends thejtiof each proof in theverificationtable. So a replay answers null on every instance.- A bound token sent as a bearer answers null (RFC 9449 section 7.2).
- At
/auth/oauth/tokenand/auth/oauth/userinfo, thehtuof a proof isbaseURLplusbasePathplus the route path.auth.callercompareshtuwith the request URL. oauth.dpop.algslists the algs of a proof, andoauth.dpop.windowSecondsthe window of itsiat, 60 seconds by default.- Another server checks a proof with the
dpopoption of the verify package. Its default replay store sees one isolate only.
Pairwise subjects
Section titled “Pairwise subjects”A client of subject_type: "pairwise" gets one subject per user and sector, so two clients of two sectors cannot join their users.
- The subject is
ps_and 16 random bytes. Core stores it, so a secret rotation never changes it. - The ID token, the access token, userinfo, and introspection carry the subject.
auth.callermaps it back to the user. - The sector of a
cl_client is the one host of its redirect URIs. A document’s sector is the host of its client id. - Two hosts, a private-use scheme, a loopback host, or an IP literal give no sector. Such a pairwise client is refused.
- Core never fetches
sector_identifier_uri. A registration with it is refused, and a document drops it. - An update that changes the sector of a pairwise client is refused. Delete the client and make a new one.
- The
userIdof the verify package is the token subject. Onlyauth.callerin the app knows the user.
Introspection
Section titled “Introspection”A resource server asks POST /auth/oauth/introspect whether a token is live now (RFC 7662).
- The caller is a confidential client with
introspect: true. Onlyapi.oauth.clientssets it. - Set
oauth.introspectionto map each client id to the resources whose access tokens it may see. - Without the map, a client sees the one resource of a single-entry
oauth.resources, and none of several. - A refresh token answers only its own client, with no map entry.
- Every other token answers
{ "active": false }with no other member. A revoke or a delete ends a token there at once. - Each call counts on
oauth-introspect:ipandoauth-introspect:client, 600 per minute each. - The
introspectoption of the verify package asks this route for each token.
Sign-in and auth_time
Section titled “Sign-in and auth_time”oauth.signInURLreplaces core’s sign-in page with the app’s own route. The route gets?request_id=oq_…alone.- After the sign-in, send the browser to
continueAuthorizeURLof@authtempo/client/oauth. - The route must ask for a new sign-in each time, also when the browser has a live session. A route that skips its form makes a redirect loop.
prompt=login,max_age=0, and a sign-in older thanmax_ageseconds send the person to the sign-in step again.- The held request then goes on only with a session signed in at or after the request.
- The ID token carries
auth_time: the session’sfreshAt, else itscreatedAt. A handoff session keeps the sign-in time of the browser session. request,request_uri, andregistrationgo back to the client asrequest_not_supported,request_uri_not_supported, andregistration_not_supported.
The refresh reuse window
Section titled “The refresh reuse window”oauth.refreshReuseSeconds is 0, off, by default. The most is 60 seconds. With it on, a spent refresh token that its own client presents again within N seconds of its use answers a new child. The client auth and the DPoP key check run first. The child of the first use is then spent, so the family keeps one live branch.
The odds. Without the window, a copy of a refresh token presented after the client’s own use deletes the family at once. Take a window of N seconds. A copy presented within N seconds of the client’s use gets an access token and a refresh token. The holder of the copy can rotate that refresh token until the client’s next refresh. That refresh presents the superseded child and deletes the family. So an attacker who holds a copy has N seconds to act. Its access then lasts until the client’s next refresh, plus at most accessTtlMinutes. For a confidential client or a bound refresh token, the copy is useless without the secret or the key. The use: a client whose answer was lost on the network retries and keeps its grant.
RFC 9700 section 4.14.2 gives no grace period for rotation, so the window is off by default. Turn it on only for clients that lose answers on bad networks.
Sign-out at the provider
Section titled “Sign-out at the provider”A relying party ends the person’s session at end_session_endpoint, GET or POST /auth/oauth/end-session (OIDC RP-Initiated Logout 1.0).
- A valid
id_token_hintof the session that the request carries ends that session at once. An expired hint still counts. - Any other request with a session answers a confirmation page. Only its yes, posted from
baseURL, ends the session. - A cross-site form post carries no
SameSite=Laxcookie. So a post with no session answers 303 to the GET of the same fields, which carries the cookie. - A frame carries no
SameSite=Laxcookie either. So a GET withSec-Fetch-Destother thandocumentand no session gets a page with a top-level link to the same GET, and no redirect. - Any other answer redirects to
post_logout_redirect_uriwithstateonly for a valid hint and an exact entry of the client’spost_logout_redirect_uris. Else core shows the signed-out page. session.afterEndfires with the reasonoidc_logout.- The route counts on
oauth-end-session:ip, 60 per 15 minutes.
Warning: a page with an ID token of its own account can learn whether a visitor has a session at the provider. Core redirects at once with no session, and shows the confirmation page with a session. The specification allows this.
Back-channel sign-out
Section titled “Back-channel sign-out”A client that registers an https backchannel_logout_uri gets a sign-out token from the server when a linked session ends (OIDC Back-Channel Logout 1.0).
- The URI needs
oauth.fetch. That fetch must refuse private addresses for these posts too: core cannot resolve a name. - A code exchange or a device grant that answers an ID token links the session to the client.
- Each end of a linked session sends one token to each linked client, an expiry too. Core first writes a row in an outbox.
- After the commit, the flow posts the token as a form. A race between a link and a sign-out delays a token, and never loses it.
- Each post has 2 seconds, and all posts of one request have 5 seconds. Core reads no byte of the answer.
- A 200 or 204 deletes the row. A throw, a timeout, 408, 429, or 5xx keeps it, and the sweep sends it again.
- The waits are 1 minute, 5 minutes, 30 minutes, then 2 hours. A row goes after its sixth attempt. Any other answer deletes the row with one log line.
- The token has
typlogout+jwt,sid, the client’ssub, theeventsclaim, no nonce, and 2 minutes of life. - The
sidis the value of the client’s ID token. A public client gets theidof the session. A pairwise client gets a keyed hash of its sector and thatid, so two sectors cannot join their users. Core stores the value with the back-channel link of the session and the client, so a new secret version does not change it. - A refresh token stays (section 2.7). The client decides what to do with it.
- Each sign-out with a linked client can take up to 2 seconds more while that client does not answer.
- On D1, the sweep steps of these posts need Workers Paid. Delete expired rows gives the counts.
The conformance run
Section titled “The conformance run”scripts/conformance/README.md holds the steps of four plans of the OpenID conformance suite. The owner runs them on a machine with Docker. No CI job runs the suite. scripts/conformance/expected-gaps.md names each module that is expected to end other than passed, with its reason. The example Worker serves a conformance mode from its own entry and its own wrangler config.
If it fails
Section titled “If it fails”The provider routes answer the codes of the OAuth table:
invalid_request: a parameter is missing, repeated, or wrong, or the held request is spent or older than 10 minutes.invalid_client: the client id is unknown, or the client auth failed.invalid_grant: the code, the refresh token, or the device code is spent, expired, or of another client.invalid_target: theresourceis not one ofoauth.resources, not the grant’s, or absent with no default.invalid_scope: a scope is unknown, or not in both scope sets of aclient_credentialsrequest.access_denied: the person refused, or the user is unverified.login_requiredandconsent_required:prompt=nonewith no session or no consent.invalid_tokenandinsufficient_scope: the userinfo bearer is not valid, or lacksopenid.invalid_dpop_proof: a DPoP proof failed a check, or the grant is bound to another key.unauthorized_client: a revoke under another client’s id, or a grant that the client does not hold.invalid_client_metadataandinvalid_redirect_uri: a registration or a client call has a field that core refuses.authorization_pending,slow_down, andexpired_token: the answers of a device poll.request_not_supported,request_uri_not_supported, andregistration_not_supported: the authorize request holds a parameter that core does not take.rate_limited: a limit of the provider is full.