New:Introducing Socket Scanning for VS Code Marketplace Extensions.Learn more →
Get Started

@cloudflare/workers-oauth-provider

Package Overview
Dependencies
Maintainers
4
Versions
73
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@cloudflare/workers-oauth-provider

OAuth provider for Cloudflare Workers

Source
npmnpm
Version
1.1.0
Version published
Weekly downloads
353K
-65.47%
Maintainers
4
Weekly downloads
 
Created
Source

OAuth 2.1 Provider Framework for Cloudflare Workers

@cloudflare/workers-oauth-provider adds OAuth 2.1 authorization to HTTP APIs and remote MCP servers running on Cloudflare Workers.

1.0 is out, with a new split API. The authorization server (OAuthAuthorizationServer) and resource server (OAuthResourceServer) are now separate classes that can run in one Worker or several; the quick start shows both. The single-Worker OAuthProvider is still supported. Upgrading from 0.x? Read the migration guide, or point your coding agent at the skill in skills/migrate-to-1.0/, which also ships in the npm package.

Install

npm install @cloudflare/workers-oauth-provider

The Worker needs a KV namespace bound as OAUTH_KV:

{
  "kv_namespaces": [
    {
      "binding": "OAUTH_KV",
      "id": "YOUR_KV_NAMESPACE_ID",
    },
  ],
}

To enable Client ID Metadata Documents, also add Cloudflare's SSRF protection compatibility flag:

{
  "compatibility_flags": ["global_fetch_strictly_public"],
}

See Client registration for the matching provider option.

Quick start

An MCP deployment has two roles. The authorization server signs users in and issues tokens. The resource server is your MCP endpoint: it accepts those tokens and checks them with the authorization server over a Service Binding. Each is one class.

Authorization server Worker

import { AuthorizationError, OAuthAuthorizationServer, type AuthRequest } from '@cloudflare/workers-oauth-provider';
import { WorkerEntrypoint } from 'cloudflare:workers';

interface Env {
  OAUTH_KV: KVNamespace;
}

const authorizationServer = new OAuthAuthorizationServer<Env>({
  issuer: 'https://auth.example.com',
  resources: ['https://mcp.example.com/mcp'],
  authorizeEndpoint: '/authorize',
  tokenEndpoint: '/oauth/token',
  scopesSupported: ['mcp:read'],

  // Preferred for clients with no pre-existing relationship.
  // Also requires global_fetch_strictly_public in wrangler.jsonc.
  clientIdMetadataDocumentEnabled: true,

  // Optional compatibility fallback. MCP 2026 deprecates DCR for new clients.
  clientRegistrationEndpoint: '/oauth/register',
});

async function authorize(request: Request, env: Env): Promise<Response> {
  const oauth = authorizationServer.getOAuthApi(env);

  // Parses the OAuth parameters and validates the client, redirect URI,
  // response type, resource indicator, and PKCE.
  let oauthRequest: AuthRequest;
  try {
    oauthRequest = await oauth.parseAuthRequest(request);
  } catch (error) {
    if (!(error instanceof AuthorizationError)) throw error;
    if (!error.redirectUri) {
      // Unknown clients and invalid redirects must be rendered locally.
      return new Response(error.description, { status: 400 });
    }
    const redirect = new URL(error.redirectUri);
    redirect.searchParams.set('error', error.code);
    redirect.searchParams.set('error_description', error.description);
    if (error.state) redirect.searchParams.set('state', error.state);
    if (error.issuer) redirect.searchParams.set('iss', error.issuer);
    return Response.redirect(redirect.href, 302);
  }

  const client = await oauth.lookupClient(oauthRequest.clientId);
  if (!client) return new Response('Unknown OAuth client', { status: 400 });

  // Authenticate the user and obtain consent here. Never approve automatically
  // in production; this example assumes those steps produced these values.
  const user = { id: 'user-123', displayName: 'Ada' };
  const { redirectTo } = await oauth.completeAuthorization({
    request: oauthRequest,
    userId: user.id,
    metadata: { clientName: client.clientName },
    scope: oauthRequest.scope.filter((scope) => scope === 'mcp:read'),
    props: { userId: user.id, displayName: user.displayName },
  });
  return Response.redirect(redirectTo, 302);
}

export default class AuthServer extends WorkerEntrypoint<Env> {
  // Your /authorize page; everything else (discovery, token, revocation, registration) is the library's.
  fetch(request: Request) {
    if (new URL(request.url).pathname === '/authorize') return authorize(request, this.env);
    return authorizationServer.fetch(request, this.env, this.ctx);
  }

  // Called by resource Workers over their Service Binding.
  validateToken(resource: string, token: string) {
    return authorizationServer.validateToken(resource, token, this.env);
  }
}

Resource server Worker

// wrangler.jsonc
{
  "services": [{ "binding": "AUTH_SERVER", "service": "auth-server" }],
}
import { OAuthResourceServer, type AuthorizationServerBinding } from '@cloudflare/workers-oauth-provider';

interface AuthProps {
  userId: string;
  displayName: string;
}

interface Env {
  AUTH_SERVER: AuthorizationServerBinding<AuthProps>;
}

export default new OAuthResourceServer<Env, AuthProps>({
  resourceMetadata: {
    resource: 'https://mcp.example.com/mcp',
    authorization_servers: ['https://auth.example.com'],
    scopes_supported: ['mcp:read'],
    resource_name: 'Example MCP server',
  },
  validateToken: (env) => env.AUTH_SERVER.validateToken,
  handler: {
    fetch(request, env, ctx) {
      // ctx.props: what completeAuthorization() stored. ctx.auth: the verified token (scope, userId, clientId, …).
      return Response.json({ userId: ctx.props.userId, scope: ctx.auth.scope });
    },
  },
});

The resource server publishes its RFC 9728 metadata, answers unauthenticated requests with a Bearer challenge that points at it, validates every token for its own resource only, and passes the handler ctx.props and ctx.auth. The handler still enforces permissions such as ownership and tenancy; insufficientScope(ctx.auth, scopes) builds the MCP 403 when a token lacks a scope an operation needs. The binding is not a URL, so the validator is not reachable from the public internet.

More resources, or one Worker

  • Another MCP resource: add it to resources and deploy another OAuthResourceServer with the same binding. A token issued for one resource is refused by every other.
  • Both roles in one Worker: construct the OAuthResourceServer next to the authorization server with a local validator, validateToken: (env) => (resource, token) => authorizationServer.validateToken(resource, token, env), and route to it from your fetch.

docs/resource-servers.md covers both, including a three-domain Hono example, and how to accept another issuer's tokens at your own risk.

Single Worker: OAuthProvider

When one Worker is both the authorization server and its only resource, which was the 0.x shape, OAuthProvider combines the two roles. Requests to apiRoute are protected and reach apiHandler with ctx.props and ctx.auth; everything else that isn't an OAuth endpoint goes to defaultHandler, which owns /authorize and reaches the same helpers as env.OAUTH_PROVIDER:

export default new OAuthProvider<Env>({
  apiRoute: '/mcp', // or apiHandlers: { '/mcp': …, '/mcp/admin': … }
  apiHandler: McpApiHandler, // an object with fetch, or a WorkerEntrypoint class
  defaultHandler, // /authorize, using env.OAUTH_PROVIDER.parseAuthRequest() / completeAuthorization()
  authorizeEndpoint: '/authorize',
  tokenEndpoint: '/oauth/token',
  scopesSupported: ['mcp:read'],
  resourceMetadata: {
    resource: 'https://mcp.example.com/mcp',
    authorization_servers: ['https://mcp.example.com'],
    scopes_supported: ['mcp:read'],
  },
  clientIdMetadataDocumentEnabled: true,
});

Every protected route must be the canonical resource path or a descendant of it; construction rejects anything else.

How MCP authorization discovery works

An MCP client discovers authorization in two stages, following the MCP authorization server discovery rules.

For an MCP endpoint at https://mcp.example.com/mcp:

  • The client sends an unauthenticated request to /mcp.

  • The provider returns 401 Unauthorized with a challenge similar to:

    WWW-Authenticate: Bearer realm="OAuth", resource_metadata="https://mcp.example.com/.well-known/oauth-protected-resource/mcp", scope="mcp:read"
    
  • The client fetches the protected resource metadata:

    https://mcp.example.com/.well-known/oauth-protected-resource/mcp
    
  • That document identifies one or more authorization server issuers through authorization_servers.

  • The client fetches RFC 8414 authorization server metadata from the selected issuer. In the quick start that is:

    https://auth.example.com/.well-known/oauth-authorization-server
    
  • The metadata tells the client where to authorize, exchange tokens, and register if registration is enabled.

Protected resource metadata and authorization server metadata serve different roles:

  • Protected resource metadata describes the MCP server and identifies its authorization servers.
  • Authorization server metadata describes OAuth endpoints and capabilities such as PKCE and CIMD.

Protected resource metadata

Every protected resource needs its own resourceMetadata.resource. Configure each canonical HTTPS identifier with a lowercase scheme and host (plain http is accepted only on a loopback host, for wrangler dev):

resourceMetadata: {
  resource: 'https://mcp.example.com/mcp',
  authorization_servers: ['https://auth.example.com'],
  scopes_supported: ['files:read'],
  bearer_methods_supported: ['header'],
  resource_name: 'Files MCP server',
}

For the example above, an unauthenticated request to the exact canonical URL receives a Bearer challenge pointing to:

https://mcp.example.com/.well-known/oauth-protected-resource/mcp

That document returns the configured canonical resource. The discovery URL is built from the canonical resource: an origin uses /.well-known/oauth-protected-resource, and a path and query are inserted after the well-known prefix.

A canonical path is the base audience for its path-boundary descendants: a token for https://mcp.example.com/mcp is accepted at /mcp/tools, and a challenge at /mcp/tools advertises the one canonical document for /mcp, as RFC 9728 §5.1 permits. A request on another origin, or one that the canonical resource does not cover, gets a challenge without resource_metadata. Every protected route must be the canonical resource path or a descendant of it; the provider rejects any other apiRoute or apiHandlers key at construction, because a token could never validate there.

authorization_servers may contain more than one issuer. Each value must use canonical HTTPS issuer spelling: lowercase scheme and host, with no userinfo, default port, dot segments, query, or fragment. As with resources, http is accepted only on a loopback host. OAuth issuer comparison is exact. The MCP client chooses an authorization server and must keep credentials and tokens separate for each issuer. new OAuthResourceServer() requires it explicitly, wherever the resource runs.

Authorization server metadata

The provider publishes RFC 8414 metadata containing:

  • issuer
  • authorization_endpoint
  • token_endpoint
  • protected_resources, containing the authorization server's registered canonical resources
  • registration_endpoint, when DCR is enabled
  • supported response and grant types
  • token endpoint authentication methods
  • PKCE methods
  • revocation endpoint
  • RFC 9207 issuer support
  • CIMD support when it is enabled and safe to use

The package serves RFC 8414 metadata rather than OpenID Connect discovery. MCP authorization servers need to provide at least one of those mechanisms, so RFC 8414 is sufficient.

Authorization endpoint

Your authorizeEndpoint belongs to the application's defaultHandler because user authentication and consent are application-specific. The provider is not an identity provider.

A typical flow has three steps:

  • Call parseAuthRequest(request) to validate the client, redirect URI, response type, resource, and PKCE restrictions.
  • Authenticate the user, show consent, and decide which scopes to grant.
  • Call completeAuthorization() and redirect to its returned redirectTo URL.

docs/consent-page.md shows a safe consent page (what it must display, escaping client metadata, Allow and Deny) and which errors to redirect back to the client and which to render.

parseAuthRequest() throws an exported AuthorizationError for expected request validation failures. Its optional redirectUri is present only after the client and exact registered redirect URI have been validated. Without it, render the error locally and never redirect. With it, the application can safely construct an OAuth error redirect using the error's code, description, original state, and RFC 9207 issuer, as shown in the quick start.

completeAuthorization() repeats response-type validation before writing a grant or revoking existing grants. Validation errors from reconstructed requests are also typed as AuthorizationError, but applications should not construct redirects from untrusted reconstructed values; the redirect context is attached only by parseAuthRequest().

completeAuthorization() stores a new grant and, by default, revokes existing grants for the same user, client, and resource after the new grant is safely stored. A grant for another registered resource is a separate authorization and is not revoked. Set revokeExistingGrants: false only when the application intentionally allows concurrent grants within the same resource.

For Client ID Metadata Document clients, whose client_id is the metadata URL shared by every installation, default revocation is additionally scoped to grants created from the same redirect URI, so one installation's re-authorization does not revoke another's. Grants created before the redirect URI was recorded are never auto-revoked by CIMD clients.

For users with many grants, revokeExistingGrantsBatchSize controls the KV page size used during that scan. It defaults to 50 and is capped at KV's maximum page size of 1000.

Authorization response issuer

RFC 9207 issuer identification is always enabled. Authorization server metadata advertises authorization_response_iss_parameter_supported: true, and successful authorization responses include iss automatically.

parseAuthRequest() returns the expected issuer. If the application creates a terminal OAuth error redirect, include that value:

const oauthRequest = await env.OAUTH_PROVIDER.parseAuthRequest(request);
const redirect = new URL(oauthRequest.redirectUri);
redirect.searchParams.set('error', 'access_denied');
redirect.searchParams.set('state', oauthRequest.state);
if (oauthRequest.issuer) redirect.searchParams.set('iss', oauthRequest.issuer);
return Response.redirect(redirect.toString(), 302);

Intermediate identity-provider redirects and local HTML error pages do not need the OAuth iss parameter.

Client registration

MCP client registration defines three ways for a client to obtain a client ID. Clients that support all three prefer pre-registration, then CIMD, then DCR.

Pre-registered clients

Use OAuthHelpers.createClient() to create clients through application or administrative code. These clients are stored in KV and are not subject to clientRegistrationTTL.

Client ID Metadata Documents

CIMD lets a client use an HTTPS URL with a non-root path as its client_id. That URL serves a JSON metadata document describing the client and its redirect URIs.

Enable it in both places:

new OAuthProvider({
  // Other options...
  clientIdMetadataDocumentEnabled: true,
});
{
  "compatibility_flags": ["global_fetch_strictly_public"],
}

The compatibility flag prevents outbound CIMD fetches from using legacy same-zone origin routing, which is necessary for SSRF protection. The provider advertises client_id_metadata_document_supported: true only when both settings are present. CIMD fetches also use the cache option of fetch, which requires a compatibility date of 2024-11-11 or later (or the cache_option_enabled compatibility flag).

CIMD validation follows draft-ietf-oauth-client-id-metadata-document-00 — the revision pinned by the MCP 2026-07-28 authorization spec — and includes:

  • An HTTPS Client Identifier URL with a path component and no userinfo, fragment, or dot path segments.
  • A document client_id exactly matching its URL.
  • Non-empty client_name and redirect_uris fields, as MCP requires, with unsafe redirect schemes rejected at ingestion.
  • Exact authorization-request redirect URI validation, with RFC 8252 loopback port handling.
  • A 5 KB response size limit and a 10 second timeout covering both headers and body.
  • Valid UTF-8 JSON object syntax and safe URI schemes for client metadata fields.
  • No embedded client secrets or private JWK material.

Validated documents are cached according to their Cache-Control headers, capped at 7 days. Error responses and invalid documents are never cached, and a cached document that stops validating is evicted and re-resolved from origin within the same request.

CIMD token endpoint authentication is negotiated from token_endpoint_auth_method and the OpenID RP Metadata Choices field token_endpoint_auth_methods_supported. The provider currently implements only none: a client may prefer private_key_jwt while also offering none, in which case the provider selects none and applies public-client PKCE requirements. A client that offers only private_key_jwt is rejected until assertion validation is implemented.

When a CIMD document cannot be fetched or validated, the token endpoint returns a generic invalid_client response and reports diagnostics through onError.internal. OAuthHelpers methods that resolve a CIMD client throw the exported CimdFetchError, allowing applications to distinguish an upstream metadata failure from a client that does not exist. See Advanced configuration for an example.

Dynamic Client Registration

Set clientRegistrationEndpoint to enable RFC 7591 Dynamic Client Registration:

clientRegistrationEndpoint: '/oauth/register';

MCP 2026-07-28 deprecates DCR for new implementations in favor of CIMD. The endpoint remains useful for compatibility with clients that do not support CIMD.

Registration accepts only authentication methods, grants, and response types implemented by the configured provider, and rejects inconsistent grant/response combinations before storage. Choice-valued token_endpoint_auth_methods_supported input is negotiated to one effective token_endpoint_auth_method; grant and response registrations remain strict. Omitted metadata uses the RFC 7591 defaults: client_secret_basic, grant_types: ["authorization_code"], and response_types: ["code"]. The token endpoint enforces each client's registered grant types with unauthorized_client; refresh_token is implied by authorization_code, and a client must register urn:ietf:params:oauth:grant-type:token-exchange to use token exchange.

The effective token_endpoint_auth_method returned by registration is enforced exactly. When both authentication metadata fields are omitted, no explicit-method marker is stored and the client may use either client_secret_basic or client_secret_post, provided the same stored secret validates. Client records written by earlier releases have no marker and receive the same compatibility. This never crosses between none and a secret method and does not apply to CIMD clients.

Calling OAuthHelpers.updateClient() with tokenEndpointAuthMethod adds the marker; unrelated updates leave it unchanged.

Related options:

  • clientRegistrationTTL controls the lifetime of dynamically registered clients. The default is 90 days. A registration still in use does not expire: once it has passed half its lifetime, the next successful token request renews it for the full TTL, so a client that keeps refreshing keeps its client_id while an abandoned one is cleaned up. The client_secret_expires_at returned at registration describes the initial lifetime; there is no channel to report a renewal, so a client that honours it re-registers on that schedule as before.
  • disallowPublicClientRegistration rejects DCR clients using token_endpoint_auth_method: "none".
  • clientRegistrationCallback can allow or reject registration based on application policy.

Clients created by OAuthHelpers.createClient() are not affected by the DCR TTL or public-registration restriction.

PKCE and token lifecycle

Public clients must use PKCE with authorization code flow. PKCE challenges use only S256 by default. Confidential clients may still omit PKCE.

Legacy deployments with clients that cannot use S256 can opt back into plain PKCE:

allowPlainPKCE: true;

allowImplicitFlow defaults to false; leave it disabled for MCP and other new OAuth deployments.

The provider owns tokenEndpoint. It exchanges authorization codes for tokens, refreshes access tokens, and handles RFC 7009 revocation. Refresh tokens rotate on use. The immediately previous token remains valid until its replacement is first used, allowing a client to retry after losing a refresh response.

A grant expires refreshTokenTTL seconds after the code exchange (30 days by default) however often it is refreshed. Set refreshTokenIdleTTL to make that lifetime slide instead: each successful refresh moves the expiry to that many seconds later, so a grant lives while the client keeps using it and expires once idle. tokenExchangeCallback can return refreshTokenIdleTTL to set the lifetime for one refresh, which lets a Worker that proxies an upstream OAuth service match the lifetime of the upstream refresh token it just rotated. See Advanced configuration.

Resources and token audiences

An authorization server may register one or more protected resources. Each resource has one canonical resourceMetadata.resource: an absolute HTTPS URI without a fragment, with lowercase https and a lowercase host, and an RFC 3986-safe producer serialization. Userinfo, default ports, dot-segment paths, and an empty path before a query are rejected because Request would rewrite them before RFC 9728 comparison. A bare origin is the only empty-path exception; use / before a query. Query components are supported but discouraged by RFC 9728.

For local development, http is accepted for resources, authorization_servers, the explicit OAuthAuthorizationServer issuer, and absolute endpoint URLs only when the host is a loopback address (localhost, 127.0.0.0/8, ::1), so wrangler dev works at http://localhost:8787. Any other host must use https: Workers are always served over https, and OAuth 2.1 requires it. A local MCP client's loopback redirect URI is unaffected by this rule; it is governed by the RFC 8252 loopback handling described under client registration.

Every authorization grant and access token is bound to exactly one registered resource. A central authorization server can therefore issue separate Calendar and Drive tokens from one KV namespace, but it never turns those into one multi-audience bearer token. Completing a new authorization for Drive does not replace the same user and client's Calendar grant.

Conforming MCP clients are required to send resource in authorization and token requests. Resource selection and compatibility work as follows:

  • When the authorization server has one registered resource, that sole resource is selected if an authorization request omits resource. This preserves existing OAuthProvider behavior.
  • When it has multiple registered resources, an authorization request must identify exactly one of them. Set defaultResource on OAuthAuthorizationServer only when older clients that omit resource should be routed to a deliberate compatibility default.
  • An authorization-code or refresh-token request may omit resource; the server inherits the resource already stored on the grant. If present, it must match that grant and cannot retarget it.
  • Malformed, unknown, or multi-valued resource input returns invalid_target before code consumption, callbacks, refresh rotation, or storage writes.

ASCII case differences in the URI scheme and host are accepted, but port, path, query, trailing slash, and array cardinality remain strict. The authorization server always stores and returns the configured lowercase scheme-and-host spelling. The token response includes the selected resource, and the access-token audience contains that resource alone.

Token exchange cannot change the resource. Both the subject-token audience and any explicit requested resource must resolve to the same registered canonical value. A token is exchanged by the client its grant was issued to unless tokenExchangeCallback returns allowCrossClientExchange: true. Internally and externally validated tokens are accepted at a protected route only when their audience matches that route's resource.

Path-aware API validation uses path-boundary prefix matching. A canonical audience for https://example.com/mcp covers /mcp and /mcp/tools, but not /mcp-other. A canonical trailing slash remains significant.

Scopes and step-up authorization

scopesSupported is published only in authorization server metadata. Configure each protected resource's resourceMetadata.scopes_supported explicitly with the minimal scopes required for its basic functionality and baseline Bearer challenges.

The application decides which requested scopes to grant through completeAuthorization({ scope }). Token and refresh requests can only narrow those scopes.

Both hosts name scopes_supported in the initial 401 challenge, so a client asks for the right scopes first time. Operation-level policy stays in the handler, which reads the token's scopes from ctx.auth.scope and answers a shortfall with insufficientScope(ctx.auth, ['files:write']): 403, error="insufficient_scope", every scope the operation needs in one challenge, and the resource's metadata URL. See docs/resource-servers.md.

Advanced features

The package also supports:

  • External API keys and bearer credentials through resolveExternalToken as an advanced compatibility feature.
  • Updating encrypted props, token scope, and token lifetimes with tokenExchangeCallback.
  • OAuth 2.0 Token Exchange when allowTokenExchangeGrant is enabled.
  • Signing users in through another OAuth provider (GitHub, Google, …) with per-client consent and browser-bound state. See docs/upstream-sign-in.md.
  • Structured callback errors through the exported OAuthError and ExternalTokenError classes.
  • Custom error observation or responses through onError.
  • Experimental MCP Enterprise-Managed Authorization using ID-JAG assertions.
  • One authorization server with multiple same-Worker or separately routed MCP resources.
  • Multiple protected handlers through apiHandlers.
  • Configurable access token, refresh token, and DCR client lifetimes.

See Advanced configuration for examples and security notes.

KV storage and cleanup

Sensitive values are not stored in plaintext:

  • Access tokens, refresh tokens, authorization codes, and client secrets are stored only by hash.
  • props are encrypted with AES-GCM using key material wrapped by the corresponding secret token.
  • Grant userId and metadata are not encrypted because applications use them to enumerate and revoke grants. Treat those fields as storage-visible metadata.

See storage-schema.md for the complete KV layout.

By default completeAuthorization() revokes the user's earlier grants for the same client and resource. It finds them from KV key metadata that every grant written by 1.0 or later carries, so the cost is one list() per thousand grants the user has, not a read per grant. Grants written before 1.0 are read individually, revokeExistingGrantsBatchSize at a time (default 50), until a refresh rewrites them with metadata.

KV TTLs remove expiring records automatically. purgeExpiredData() provides a manual sweep for orphaned or expired grants and tokens:

const provider = new OAuthProvider({
  // Options...
});

export default {
  fetch(request, env, ctx) {
    return provider.fetch(request, env, ctx);
  },
  async scheduled(_event, env) {
    const result = await provider.purgeExpiredData(env, { batchSize: 100 });
    console.log(result);
  },
};

The default batch size is 50. result.done reports whether both key spaces were scanned completely during that invocation.

Deleting a client through OAuthHelpers.deleteClient() also revokes its grants and associated tokens across users.

Configuration reference

The existing OAuthProvider combined configuration uses these options:

OptionPurposeDefault
apiRoute and apiHandlerProtect one or more route prefixes with one handlerUse these or apiHandlers
apiHandlersMap protected route prefixes to different handlersUse this or apiRoute plus apiHandler
defaultHandlerHandle authorization UI and other unprotected routesRequired
authorizeEndpointApplication-owned authorization and consent endpointRequired
tokenEndpointProvider-owned token and revocation endpointRequired
clientRegistrationEndpointEnable RFC 7591 DCRDisabled
scopesSupportedPublish authorization server scopesOmitted
resourceMetadata.resourceCanonical HTTPS resource and token audienceRequired
clientIdMetadataDocumentEnabledEnable CIMD lookup and advertisementfalse
cookiePrefixPrefix for the consent and upstream helpers' cookies (must be __Host-…)__Host-oauth-
allowPlainPKCEPermit the legacy plain PKCE methodfalse
allowImplicitFlowEnable implicit token responsesfalse
disallowPublicClientRegistrationReject public clients at DCRfalse
clientRegistrationCallbackApply application policy before storing a DCR clientNone
allowTokenExchangeGrantEnable RFC 8693false
tokenExchangeCallbackUpdate props, scopes, or lifetimes during token exchangeNone
resolveExternalTokenValidate external bearer credentials (advanced)None
enterpriseManagedAuthorizationEnable experimental ID-JAG grant supportDisabled
onErrorObserve or replace OAuth error responses; internal names the failed checkLogs a warning

The functional role API adds these surfaces without removing OAuthProvider:

SurfacePurpose
new OAuthAuthorizationServer({ issuer, resources, … })Create the AS role with a canonical RFC 8414 issuer and its fixed resource registry
validateToken(resource, token, env)Validate an access token for one declared resource; what a resource server calls
defaultResourceSelect a deliberate default for new authorization requests that omit it
legacyGrantResourceSelect the server-controlled migration target for old unbound grants
getOAuthApi(env)Obtain OAuth helpers for an application-owned authorization route
new OAuthResourceServer({ … })Host one resource, in this Worker or another; validateToken points at the AS or a binding

Consult the exported OAuthProviderOptions, OAuthAuthorizationServerOptions, resource-server callback interfaces, and JSDoc in src/oauth-provider.ts for the complete typed API.

OAuth helpers

Handlers receive env.OAUTH_PROVIDER, which implements OAuthHelpers. It can:

  • Parse authorization requests and complete authorization.
  • Run a consent page and a third-party sign-in redirect safely (beginConsent(), approveConsent(), denyConsent(), isConsentRemembered(), beginUpstream(), finishUpstream()).
  • Look up, create, list, update, and delete clients.
  • List and revoke grants for a user.
  • Inspect internally issued tokens with unwrapToken().
  • Exchange access tokens when RFC 8693 is enabled.
  • Purge expired and orphaned KV data.

getOAuthApi(options, env) provides the same helper API outside a fetch handler, including RPC methods and other Worker entrypoints.

Standards

The package implements or supports the relevant portions of:

Development

Node 24 or newer is required.

npm install
npm run build
npm run check
npm run prettier

Changes that affect behavior or the public API need a Changeset. See AGENTS.md for repository conventions and SECURITY.md for vulnerability reporting.

Project history

Kenton Varda's original account of how this library was created is preserved in HISTORY.md.

FAQs

Package last updated on 24 Sep 2026

Related posts