Skip to content

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.

  • A working setup from a getting started tutorial.
  • jwtMint on. 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.
  1. Set oauth.resources to the URLs of the resources that a client may ask for, 1 to 20.
  2. Set oauth.scopes to the scopes of your app, each with the text of the consent page.
  3. Keep registration.cimd off.
    • To turn it on, pass oauth.fetch, your own fetch that refuses private addresses.
    • Set registration.dynamic: true to serve POST /auth/oauth/register. It is off by default.
  4. Mount auth.wellKnown(request) for every path that starts with /.well-known/ at the origin root.
  5. In each resource route, read the caller with auth.caller(request).
    • Answer 401 to a caller that is not kind: "oauth".
    • Answer c.subject to the client, never c.user.id. c.subject is the user id for a public client and the pairwise subject for a pairwise client. c.user is for the app.
  6. Check the scope of each tool in the route. A token with only openid must not call a tool.
The provider config and an MCP route
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 });
}
The metadata and the registration as a test
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"]]]);
});
});
  1. Build a “connected apps” page with client.oauth.grants() and client.oauth.revoke({ clientId }).
  • 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/register while registration.dynamic is on, or its client id is the https URL of its metadata document. api.oauth.clients.create makes a client in your own code. The sweep deletes a client of the registration after 90 idle days, and keeps a client of api.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", aud the resource, and lives accessTtlMinutes. 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 its grant_types hold refresh_token, as the default list does. Without it, the scope of the answer and of the access token leaves out offline_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_id answers unauthorized_client and revokes nothing.
  • A browser client on another origin can call /auth/oauth/token from a web origin of its own redirect URIs. That holds for a public client only. The answer carries access-control-allow-origin with that origin and no credentials. Its form post to /auth/oauth/revoke, and its POST /auth/oauth/userinfo with no body, answer 403 origin_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_metadata and scope, and its 403 with error="insufficient_scope". The functions unauthorizedResponse and insufficientScopeResponse of 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 resource answers invalid_target. Set oauth.defaultResource to one entry of oauth.resources for a client that cannot send resource. A named resource always wins.

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_jwt client take their own method only. An empty client_secret counts as omitted.
  • After an Authorization header, a failed client auth answers 401 invalid_client with WWW-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, introspection oauth-introspect:ip, and the device start oauth-device:ip. A failed auth of a device poll also counts on oauth-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 openid with a non-empty nonce (RFC 9700 section 2.1.1).
  • The assertion of private_key_jwt has the client id as iss and sub, and the issuer alone as aud. The token endpoint URL as aud is refused (draft-ietf-oauth-rfc7523bis-11).
  • An assertion lives at most 300 seconds, with 30 seconds of skew. Its jti works once. The algs are EdDSA, Ed25519, ES256, RS256, and PS256.
  • A registration that omits token_endpoint_auth_method gets none, not the client_secret_basic of 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) and client_secret_expires_at: 0 once. 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:

  • create makes a client of kind api. 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, and delete. list answers newest first, 100 per page, with a cursor. update changes every field but the id, the method, and the secret.
  • delete removes the client with its consents, refresh tokens, device grants, session links, and pending sign-out posts.
  • rotateSecret answers a new secret. The old one passes for keepOldHours more, 0 to 168, 24 by default.
  • Each call answers an OAuth result. An unknown id answers invalid_client.
  • Only create and update take client_credentials, credentialsScopes, and introspect.

A service that acts for no person uses the client_credentials grant:

  • Its client is confidential, and its grantTypes hold the grant. A public client, or a client without the grant, answers unauthorized_client.
  • A scope of the grant must be in both credentialsScopes and oauth.scopes. With no scope, the token gets every scope in both.
  • The answer holds no refresh token and no ID token. auth.caller answers the token as kind: "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:ip counts each request first, so a service on one IP gets 60 tokens per 15 minutes (limits). Keep the token until its expires_in ends.
A service client and a device client in code
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;
}
The client_credentials grant and the device flow as a test
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";

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, with redirect: "manual", 10 seconds, and 8 KB at most. It keeps the document one hour per isolate.
  • The document’s client_id must equal its URL.
  • A document with client_secret or client_secret_expires_at is refused (-02 section 4.1). So is a method other than none or private_key_jwt.
  • A private_key_jwt document with jwks or jwks_uri is 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_types or response_types that it does not serve, and an id_token_signed_response_alg other than jwtMint.alg.
  • A pairwise document loses sector_identifier_uri and the device grant of its grant_types.
  • Core drops a backchannel_logout_uri that is not valid, is off the host of the document, or has no oauth.fetch to post to it. It also drops a backchannel_logout_session_required that is not a boolean.
  • A document with no authorization_code grant or no code response type is refused.
  • When a document changes from private_key_jwt to none, core revokes every refresh token and deletes every device code of the client in the same write.

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.

  1. Give a client the grant urn:ietf:params:oauth:grant-type:device_code.
  2. The device posts to POST /auth/oauth/device_authorization with its client auth, scope, and resource.
  3. The device shows user_code and verification_uri to the person.
  4. The person opens GET /auth/oauth/device, signs in, and types the code.
  5. The page shows the client, the scopes, and the line “Approve only a device that is in front of you.”
  6. The device polls /auth/oauth/token with device_code, every interval seconds.
  • The user code is XXXX-XXXX of the letters BCDFGHJKLMNPQRSTVWXZ. It lives oauth.device.codeTtlMinutes, 10 minutes by default.
  • verification_uri_complete fills the field. The person still submits it.
  • A poll before the decision answers authorization_pending. A poll within interval seconds answers slow_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 on oauth-token:ip.
  • A deny answers access_denied, and an expired code expired_token. An approved code gives its tokens once, then invalid_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 DPoP header with a proof on a grant at /auth/oauth/token. The access token then holds cnf.jkt, and token_type is DPoP.
  • 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_jkt at the authorize step binds the code to a key. The exchange then needs a proof of that key.
  • A client of dpop_bound_access_tokens must send a proof on every grant.
  • A resource gets Authorization: DPoP <token> and a proof for its URL and method. auth.caller checks the proof, and c.dpopJkt holds the thumbprint.
  • auth.caller spends the jti of each proof in the verification table. 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/token and /auth/oauth/userinfo, the htu of a proof is baseURL plus basePath plus the route path. auth.caller compares htu with the request URL.
  • oauth.dpop.algs lists the algs of a proof, and oauth.dpop.windowSeconds the window of its iat, 60 seconds by default.
  • Another server checks a proof with the dpop option of the verify package. Its default replay store sees one isolate only.

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.caller maps 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 userId of the verify package is the token subject. Only auth.caller in the app knows the user.

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. Only api.oauth.clients sets it.
  • Set oauth.introspection to 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:ip and oauth-introspect:client, 600 per minute each.
  • The introspect option of the verify package asks this route for each token.
  • oauth.signInURL replaces 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 continueAuthorizeURL of @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 than max_age seconds 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’s freshAt, else its createdAt. A handoff session keeps the sign-in time of the browser session.
  • request, request_uri, and registration go back to the client as request_not_supported, request_uri_not_supported, and registration_not_supported.

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.

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_hint of 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=Lax cookie. So a post with no session answers 303 to the GET of the same fields, which carries the cookie.
  • A frame carries no SameSite=Lax cookie either. So a GET with Sec-Fetch-Dest other than document and 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_uri with state only for a valid hint and an exact entry of the client’s post_logout_redirect_uris. Else core shows the signed-out page.
  • session.afterEnd fires with the reason oidc_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.

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 typ logout+jwt, sid, the client’s sub, the events claim, no nonce, and 2 minutes of life.
  • The sid is the value of the client’s ID token. A public client gets the id of the session. A pairwise client gets a keyed hash of its sector and that id, 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.

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.

The provider routes answer the codes of the OAuth table: