Tokens, scopes, and resources
Control which tokens the provider issues, for which APIs, and for how long.
Token endpoint
POST /oauth2/token supports the authorization_code, client_credentials, and refresh_token grants. Companion plugins add the device code, token exchange, and CIBA (Client-Initiated Backchannel Authentication) grants. A confidential client must authenticate with the method it registered, using one of the methods from RFC 6749 §2.3.1 and OIDC Core §9:
| Method | How the client authenticates |
|---|---|
client_secret_basic | client_id and client_secret in an HTTP Basic Authorization header (default) |
client_secret_post | client_id and client_secret in the request body |
private_key_jwt | A signed JWT assertion. See Private key JWT. |
none | Public client. PKCE is required. |
To get a JWT access token, include a resource in the request and enable the JWT plugin. The token's aud is that resource. When the scopes also include openid, aud is an array that also holds the UserInfo endpoint URL. If either is missing, or the resource uses opaque access tokens, the access token is opaque. Error codes are listed in Token errors.
An authorization_code request that omits resource uses the resources bound to the authorization code, and a refresh request uses the resources stored on the refresh token. When no resource is named or bound, including on client_credentials requests that omit resource, the access token is opaque with no aud claim, and the provider applies no default resource. RFC 8707 §2.1 says a provider can process an authorization request that omits resource without a specific resource, use a default resource, or fail the request with invalid_target. Entro Auth processes it without a resource. A resource server that sets audience rejects the resulting token.
The OAuth provider sets typ: at+jwt on JWT access tokens. Introspection, revocation, UserInfo, and token exchange require that header type when accepting a JWT as an access token. RFC 9068 §2.1
Scopes
To control which scopes your clients may request, set scopes. It defaults to ["openid", "profile", "email", "offline_access"]. Your provider acts as an OpenID provider only when the list includes openid.
| Scope | Grants |
|---|---|
openid | An ID token and the sub claim |
profile | name, picture, given_name, and family_name at UserInfo |
email | email and email_verified at UserInfo |
offline_access | A refresh token, when the client is registered for refresh_token or authorization_code |
Standard claims are returned at UserInfo, not in the ID token, as OIDC Core §5.4 describes for flows that issue an access token.
oauthProvider({
scopes: ["openid", "profile", "offline_access", "read:post", "write:post"],
})Requests that omit scope
With requireOpenId: true, an authorization request must explicitly include openid in scope. Omitting scope returns invalid_scope before the provider applies any defaults.
By default, when an authorization request leaves out scope, the provider applies a default, as RFC 6749 §3.3 allows. The default depends on whether you set clientRegistrationDefaultScopes:
- Set: the request gets only the client's scopes that are also in that list. A scope you list in
clientRegistrationAllowedScopesstays available to the client, but the client must ask for it by name. - Not set: the request gets every scope the client may request. That is the client's stored
scope, orscopeswhen the client has none.
A request that names scope is checked against the client's scopes and used as sent. The consent page shows the default. The authorization code and the token carry the scopes the user approves there, which can be fewer.
If the default list leaves out openid, the request is plain OAuth and the token response has no ID token. A request that omits scope but sends claims then fails with invalid_request, because claims needs openid. If no scope remains, for example with clientRegistrationDefaultScopes: [], the token has no scopes.
Resources
A resource is a protected API that your provider issues access tokens for. Its identifier is the resource parameter value from RFC 8707 §2 and becomes the aud of a JWT access token.
A client can get access tokens only for resources it is linked to. The authorize and token endpoints reject any other resource with invalid_target. To link a client, pass resources to adminCreateOAuthClient or call adminLinkClientResource. Setting enforcePerClientResources: false lets any client request any enabled resource, which removes the per-client audience restriction. With dynamic registration or CIMD, a client anyone registered could then get tokens for every enabled API. Keep the default, true, and link clients explicitly or through clientRegistrationDefaultResources.
oauthProvider({
resources: [
"https://api.example.com",
{
identifier: "https://api.example.com/mcp",
allowedScopes: ["mcp:read", "mcp:write"],
accessTokenTtl: 300, // 5 minutes, in seconds
},
],
})A string uses the plugin defaults. An object sets per-resource policy:
| Field | Effect |
|---|---|
name | Label for admin screens. |
allowedScopes | Requested scopes are narrowed to this list. If none remain, the request fails with invalid_scope. |
accessTokenTtl | Access token lifetime in seconds. Defaults to accessTokenExpiresIn. |
refreshTokenTtl | Refresh token lifetime in seconds. Defaults to refreshTokenExpiresIn. |
accessTokenFormat | "jwt" or "opaque". Defaults to resourceDefaults.accessTokenFormat, then "jwt". |
signingAlgorithm | Access token signing algorithm. When unset, the JWT plugin selects the signing key. |
signingKeyId | Key ID to sign this resource's access tokens with. |
customClaims | Claims added to every access token for this resource. Reserved JWT claims are stripped. |
dpopBoundAccessTokensRequired | Issue only DPoP-bound tokens for this resource. |
disabled | Stop issuing tokens for this resource. Tokens already issued still verify until they expire. |
In a request for several resources, a signingAlgorithm or signingKeyId set on one of them applies to the whole token, and resources without one do not conflict with it. The request fails with invalid_request only when two resources set different values, because one token carries one signature. To fix it, set the same value on both resources, or leave it unset on one of them.
Omit allowedScopes (or pass null) to allow every requested scope. A non-empty array is an allowlist; scopes outside it are removed and an empty intersection is rejected with invalid_scope. In config, an empty array ([]) is rejected at construction to prevent ambiguity with blocking access (use disabled: true to stop issuing tokens). Pass null through the admin API to remove the restriction; [] is rejected there too. Admin responses serialize an unrestricted allowlist as null, which echoes back cleanly.
In a request for several resources, the granted scopes are narrowed to the intersection of the allowedScopes of the requested resources. A resource without allowedScopes does not restrict, and accepts any requested scope.
RFC 8707 §2.2 says a request for several resources asks for a token that is usable at all of them, and that the provider should downscope the token to what each resource needs. Entro Auth issues one scope set for every requested resource instead. A scope that one resource disallows is dropped for all of them, including resources that allow it. The token's scope does not record which resource each scope was meant for, so use scope names that mean the same thing at every resource a client can request together.
The resources you configure are written to the oauthResource table at startup. Set resourceSeedMode to choose what happens to a row that already exists:
insertOnly(default): only adds missing rows, so edits made through the admin endpoints survive restarts.merge: adds missing rows and updates the fields present in the config. Inmergeseed mode, omittingallowedScopespreserves the existing row's allowlist; to clear an existing allowlist, use the admin update endpoint withallowedScopes: null(persisted as[]), or re-seed usingoverwritemode.overwrite: replaces existing rows with the config values.
Each instance reads the table once per configured resource to seed it. If you build Entro Auth per request, for example on Cloudflare Workers with a database client per request, those reads run on every request. Set resourceSeedScope: "process" to remember each seeded entry for the life of the process instead, as long as every instance in the process uses the same database.
Access token format
A resource gets JWT access tokens by default, when the request names it and the JWT plugin is enabled. Its API can verify a JWT locally with your JWKS, without calling the provider. A JWT stays valid until it expires, unless you turn on revocableJwtAccessTokens and the API introspects it.
To issue opaque reference tokens for a resource instead, set accessTokenFormat: "opaque" on it. The API must then introspect each token, or call verifyResourceRequest when the API runs on the auth server. An opaque token keeps the resource as its audience, so introspection reports it in aud. Revoking the token or deleting the resource cuts off access on the next introspection.
To change the format for every resource that does not set its own, use resourceDefaults:
oauthProvider({
resourceDefaults: { accessTokenFormat: "opaque" },
resources: [
"https://internal.example.com", // opaque
{ identifier: "https://api.example.com", accessTokenFormat: "jwt" },
],
})A request without a resource still gets an opaque token, because a JWT access token needs an audience. When disableJwtPlugin is true, every access token is opaque.
Startup seeding follows resourceSeedMode. With the default, insertOnly, adding accessTokenFormat to a resource that is already stored has no effect. Change the stored row with adminUpdateOAuthResource, or seed with merge.
One token cannot be both a JWT and an opaque token. A request for several resources whose formats differ fails with invalid_target (RFC 8707 §2.2). The client must request them in separate token requests.
Manage resources at runtime
To change resources without a restart, call these server-only endpoints. Each one needs a session. resourcePrivileges decides which users may call them. Without resourcePrivileges, any signed-in user may.
| Server method | Method | Path |
|---|---|---|
adminCreateOAuthResource | POST | /admin/oauth2/resources |
adminListOAuthResources | GET | /admin/oauth2/resources |
adminGetOAuthResource | GET | /admin/oauth2/resources/:identifier |
adminUpdateOAuthResource | PATCH | /admin/oauth2/resources/:identifier |
adminDeleteOAuthResource | DELETE | /admin/oauth2/resources/:identifier |
adminLinkClientResource | POST | /admin/oauth2/resources/:identifier/clients/:client_id |
adminUnlinkClientResource | DELETE | /admin/oauth2/resources/:identifier/clients/:client_id |
await auth.api.adminLinkClientResource({
params: { identifier: "https://api.example.com", client_id: clientId },
headers,
});Deleting a resource makes introspection report its tokens as inactive, while disabled: true only stops new issuance. If your API verifies JWTs locally with the JWKS, it keeps accepting them until they expire. Use introspection if you need deletion to cut off access immediately. To attach resources during dynamic registration, see Resources for registered clients.
Migration warning: Resources whose stored allowedScopes is empty currently refuse every token. This includes Prisma rows where SQL NULL was read back as []. After upgrading, those resources allow every requested scope. If you relied on an empty array to block a resource, set disabled: true for it through the admin update endpoint before upgrading; config-level disabled: true reaches existing rows only in merge or overwrite seed mode. Existing rows are not rewritten and no database migration is required. A resources entry with allowedScopes: [] now fails validation.
Lifetimes
All values are in seconds.
| Option | Default | Applies to |
|---|---|---|
accessTokenExpiresIn | 3600 (1 hour) | Access tokens issued for a user, or a function that decides it per grant |
m2mAccessTokenExpiresIn | 3600 (1 hour) | Access tokens from client_credentials |
idTokenExpiresIn | 36000 (10 hours) | ID tokens |
refreshTokenExpiresIn | 2592000 (30 days) | Refresh tokens |
codeExpiresIn | 600 (10 minutes) | Authorization codes |
assertionMaxLifetime | 300 (5 minutes) | private_key_jwt client assertions |
A refresh token's lifetime restarts at each refresh: the replacement token gets a new refreshTokenExpiresIn window. A client that refreshes regularly therefore keeps its grant indefinitely. To end a grant, revoke the refresh token. Deleting the user's consent also ends the grants issued under it. See Revoke tokens with a consent.
To shorten access tokens that carry high-privilege scopes, set scopeExpirations. A resource's accessTokenTtl and refreshTokenTtl can also shorten these lifetimes, but not extend them. When several limits apply, the earliest expiry wins. For example, with the config below, a token with both read:payments and write:payments expires after 5 minutes.
oauthProvider({
scopeExpirations: {
"write:payments": "5m", // 5 minutes after issuance
"read:payments": "30m", // 30 minutes after issuance
},
})Per-grant access token lifetime
To decide the lifetime of a user access token per grant, such as when the user picks how long a connection may last, set accessTokenExpiresIn to a function. It runs each time a grant is issued or refreshed.
oauthProvider({
accessTokenExpiresIn: ({ user, client, scopes, grantType }) =>
scopes.includes("write:payments") ? 300 : 3600,
})- The function gets copies of the grant, and nothing from the request. It receives the
user, theclient, thescopes, and thegrantType. A client cannot lengthen its own token by asking. - A throw fails the token request. The error reaches the client and no token is stored.
- An unusable result falls back to 1 hour. A result below one second, or one that is not a finite number, gets 3600 seconds, or
accessTokenMaxExpiresInwhen that is lower. A fraction is rounded down first, so0.5is unusable. - A result above
accessTokenMaxExpiresInis lowered to it. The default is 3600. To let the function return more, setaccessTokenMaxExpiresIn, for exampleaccessTokenMaxExpiresIn: 86400. Every window that has to outlast a token, such as the grant revocation entry and the record of a redeemed code, lasts that long, whatever the function returns for a grant. client_credentialstokens are unaffected. They usem2mAccessTokenExpiresIn.scopeExpirationsand a resource'saccessTokenTtlstill apply. The earliest expiry wins.
Authorization code reuse
An authorization code works once. A second token request with the same code is rejected. When that request comes from the client the code was issued to, the provider also revokes the refresh tokens and opaque access tokens issued from the code. JWT access tokens stay valid until they expire (OAuth 2.1 §7.5.3). The request comes from the issuing client when:
- It carries that client's
client_id, and a confidential client also authenticates with its credentials. - It carries the matching
code_verifier, if the code was issued with PKCE. Public clients always use PKCE, so a public client's code can only be used to revoke with itscode_verifier.
A request that fails either check is rejected and the tokens stay valid. This includes a confidential client that sends its secret but leaves out the code_verifier for a code issued with PKCE. Someone who has the code but not the code_verifier therefore cannot revoke the client's tokens.
The tokens issued from a code can outlive the code, so the provider remembers a redeemed code for as long as those tokens can still be valid. The record lasts for the longer of accessTokenExpiresIn and refreshTokenExpiresIn after redemption (30 days by default), where a function accessTokenExpiresIn counts as its accessTokenMaxExpiresIn, and each refresh-token rotation extends it by the same amount. A reuse after the code expires still revokes the tokens while that record exists.
The record is a verification value whose identifier starts with oauth_consumed_code:, unless verification.storeIdentifier hashes it. If a verification.create.before hook returns false for it, the token request still succeeds, and the provider logs an error. A later reuse of that code is then rejected without revoking its grant.
Two token requests can send one code at the same time, for example when a client retries a request it thinks timed out. The request that consumes the code starts issuing tokens. The other one is a reuse, so it fails and revokes the code's grant. If the first request is still issuing tokens, it finds the grant revoked and also fails with invalid_grant. If it already finished, the revocation revokes the tokens it returned, as for any reuse. Either way, the client must start a new authorization request.
Two requests with the same DPoP proof can end differently, because the server records the proof's jti before it consumes the code. If the second request finds the code before the first consumes it, the second then fails on the recorded jti with invalid_dpop_proof. It revokes nothing, and the first request keeps its tokens. If it arrives after the code is consumed, it is a reuse as described above.
Refresh tokens
When a refresh rotates the token, it issues a new refresh token and invalidates the old one, following OAuth 2.1 §4.3.1. Reusing a rotated refresh token is treated as replay: the refresh tokens of its grant are revoked, and the opaque access tokens they issued are deleted. A grant is everything one authorization produced, whether an authorization code, a device code, or a CIBA request started it. The user's other grants with the same client keep working. JWT access tokens stay valid until they expire. With revocableJwtAccessTokens, the replayed grant's JWT access tokens are revoked too. After a replay, the refresh fails with invalid_grant, and the client must start a new authorization request to get tokens. A refresh of the replayed token's grant that is still issuing tokens when the replay arrives also fails with invalid_grant, and the tokens it stored are deleted. This needs a replayed token with a grant ID.
A refresh token with no grant ID, such as one rotated or revoked before you upgraded to 1.8, cannot name a grant. A replay of it deletes every refresh token the user holds for that client, as it did before 1.8, and the opaque access tokens linked to them. It does not stop a refresh that is still issuing tokens under it.
A refresh that narrows the scope to drop offline_access still returns a new refresh token, but that token lacks offline_access. Refreshing it later returns no new refresh token, so the client keeps the one it has.
A refresh keeps the sid of the session that authorized the grant while that session is live. What happens once the session has expired or been deleted depends on offline_access:
- With
offline_access, the refresh still succeeds, and the new access and ID tokens omitsidso that introspection and UserInfo accept them. A refresh that would dropoffline_access, through a narrowerscopeor a resource's allowed scopes, fails withinvalid_grantinstead, and the presented refresh token keeps working. - Without
offline_access, the refresh token ends with its session. The refresh fails withinvalid_grant, and introspection reports the refresh token inactive.
Tokens from the device authorization and CIBA grants have no associated session, so neither case applies to them.
Keep the default, 0, unless your clients lose refresh responses. To let a client retry a refresh after a lost response, set refreshTokenReuseInterval to a number of seconds. A retry within that window gets the same response back, including the replacement refresh token. Overlapping in-flight refreshes of the same token get that response too: the duplicate waits for the first request to store it, for at most 5 seconds, and fails with invalid_grant if it does not appear. The retry gets that response only when it uses the same client, scopes, resources, and DPoP key as the first refresh. A retry that differs but is otherwise valid gets invalid_grant.
Inside the window, reuse is not treated as replay, and the token family is never revoked. A stolen rotated token that passes these checks therefore gets the replacement refresh token. Keep the interval short.
oauthProvider({
refreshTokenReuseInterval: 5, // 5 seconds
})To change the string sent to the client, set formatRefreshToken. encrypt receives the generated refresh token (before it is hashed for storage) and, when there is one, the session ID. It returns the string sent to the client, before the provider adds prefix.refreshToken. decrypt receives the string the client sends back, without the prefix.refreshToken prefix. It must return an object with the token that encrypt received and, optionally, the sessionId.
When the value is not a refresh token, decrypt should throw an APIError with status 400. An error from jose, such as the one compactDecrypt throws, counts the same when your app and the provider resolve the same copy of jose. If they resolve different copies, catch the error and throw an APIError with status 400.
When decrypt throws either error, the provider treats the value as not a refresh token. A refresh with that value fails with invalid_grant. Revocation and introspection go on to check the other token types. Any other error fails the request with a server error. That includes a key set failure from jose (JWKSTimeout, JWKSInvalid, or JWKSMultipleMatchingKeys), which means decrypt could not run, not that the value is not a refresh token. Revocation and introspection can also pass access tokens to decrypt.
The first example below does not throw. When decrypt does not recognize the value, it returns { token: value }. A refresh token sent to the client without the format keeps working, such as one issued before you set formatRefreshToken or one issued without a session ID. For any other value, the provider finds no refresh token. The result is the same as when decrypt throws.
oauthProvider({
formatRefreshToken: {
encrypt: (token, sessionId) => (sessionId ? `1.${token}.${sessionId}` : token),
decrypt: (value) => {
const [version, token, sessionId] = value.split(".");
return version === "1" && token && sessionId ? { token, sessionId } : { token: value };
},
},
})To encrypt the refresh token as a JWE:
import { entroAuth } from "@entro314labs/entro-auth";
import { base64url, CompactEncrypt, compactDecrypt } from "jose";
import { oauthProvider } from "@entro314labs/entro-auth-oauth-provider";
// A random 256-bit key kept in your secret store, base64url-encoded.
// Generate one with `openssl rand -base64 32 | tr '+/' '-_' | tr -d '='`.
const key = base64url.decode(process.env.REFRESH_TOKEN_KEY!);
const alg = "A256KW";
const enc = "A256GCM";
const auth = entroAuth({
plugins: [
oauthProvider({
formatRefreshToken: {
encrypt: async (token, sessionId) => {
const value = JSON.stringify({ sessionId, token });
return new CompactEncrypt(new TextEncoder().encode(value))
.setProtectedHeader({ alg, enc })
.encrypt(key);
},
decrypt: async (token) => {
const { plaintext } = await compactDecrypt(token, key);
return JSON.parse(new TextDecoder().decode(plaintext));
},
},
}),
],
});PKCE
PKCE (RFC 7636) is required for every authorization code flow, and only the S256 method is accepted. To let an admin-created confidential client skip PKCE, set require_pkce: false on it. That client then has no protection against intercepted or injected authorization codes beyond its secret and state (RFC 9700 §2.1.1). Public clients cannot opt out. For dynamically registered confidential clients, set the default with clientRegistrationRequirePKCE.
await auth.api.adminCreateOAuthClient({
headers,
body: {
redirect_uris: ["https://app.example.com/callback"],
token_endpoint_auth_method: "client_secret_post",
require_pkce: false,
},
})A client without PKCE that requests offline_access must send both openid and nonce. Keep PKCE on unless a legacy client cannot send it, as OAuth 2.1 §7.5.1 recommends.
DPoP
DPoP stops anyone who lacks the client's private key from replaying a leaked access token, as long as your API verifies the proof. A DPoP-bound token works only alongside a proof signed by that key.
A client gets DPoP-bound tokens (RFC 9449) in any of these cases:
- It registered with
dpop_bound_access_tokens: true(§5.2). - It sends
dpop_jkton the authorization request. - It requests a resource with
dpopBoundAccessTokensRequired: true. - It sends a
DPoPproof with the token request.
The token endpoint then requires a DPoP proof (§5) and returns token_type: "DPoP". A refresh needs a proof from the same key. So does a token exchange of the client's own token. A JWT access token carries the key's thumbprint in cnf.jkt. The client calls your API with Authorization: DPoP <access_token> and a DPoP proof that includes the access token hash, ath (§7).
oauthProvider({
dpop: {
proofMaxAgeSeconds: 300, // 5 minutes, in seconds (the default)
signingAlgorithms: ["ES256", "EdDSA"],
},
})Set baseURL to the public URL clients call. Otherwise proofs fail behind a proxy that rewrites the host, because the expected htu comes from baseURL, not from the request host.
To verify DPoP-bound tokens in your API, see Protect your API.
Send DPoP requests from a client
@entro314labs/entro-auth/oauth2/dpop-client signs proofs and handles nonces for a client app, such as a single-page app, a native app, a CLI, or an MCP client. It uses only the standard Web Crypto and Fetch APIs, which browsers, Node.js, Bun, Deno, and Cloudflare Workers provide, so it adds no server code to a client bundle. The same module is also available as @entro314labs/entro-auth-core/oauth2/dpop-client.
Create a key pair once, then send token and API requests through createDpopFetch:
import {
createDpopFetch,
generateDpopKeyPair,
} from "@entro314labs/entro-auth/oauth2/dpop-client";
const keyPair = await generateDpopKeyPair();
const dpopFetch = createDpopFetch({ keyPair });
const tokenResponse = await dpopFetch("https://auth.example.com/api/auth/oauth2/token", {
method: "POST",
body: new URLSearchParams({
grant_type: "authorization_code",
code,
redirect_uri: "https://app.example.com/callback",
client_id: "my-client",
code_verifier: codeVerifier,
}),
});
const { access_token } = await tokenResponse.json();
const items = await dpopFetch("https://api.example.com/items", {
headers: { Authorization: `DPoP ${access_token}` },
});createDpopFetch works like fetch, and for each request it:
- Signs a new proof for the request's method and URL, and sends it in the
DPoPheader. - Adds the access token hash,
ath, when the request has anAuthorization: DPoPheader. - Includes the latest nonce from the request's origin. Nonces are kept per origin, so an authorization server and an API on different origins never overwrite each other's nonce.
- Retries once when the server answers
use_dpop_noncewith a new nonce. Any other response, including a seconduse_dpop_nonce, comes back unchanged. - Sends a streamed body only once, so a large upload is never held in memory for a retry. This covers a
ReadableStreambody and aRequestwhose body you don't replace in the second argument. The nonce from the response still applies to the next request. Pass a string,URLSearchParams,FormData, orBlobbody to get the retry. - Signs each proof for the origin and path it requests. If a DPoP endpoint redirects to a different origin or path, the target rejects the proof, so don't put DPoP endpoints behind such redirects.
On a redirect to another origin, fetch drops the Authorization header but still sends the DPoP header, so the other origin receives the proof without the access token. To decide whether to follow a redirect yourself, pass redirect: "manual" on a server, where the response exposes the Location header. Browsers hide the target of a manual redirect.
generateDpopKeyPair creates an ES256 key whose private half cannot be exported. Tokens issued for a key only work with that key, so keep the key pair for as long as you keep the tokens. In a browser, store the CryptoKeyPair in IndexedDB, which preserves a non-exportable key. To use another algorithm, pass a key pair from crypto.subtle.generateKey for one that Entro Auth accepts by default: ECDSA P-256 (ES256) or P-521 (ES512), Ed25519 (EdDSA), or an RSA key with SHA-256 and either PKCS #1 v1.5 (RS256) or PSS (PS256) padding. Its public key must be exportable, which it is by default.
To bind the authorization code to the key before the token request, send the key's thumbprint as dpop_jkt on the authorization request (§10):
import { deriveDpopKeyJkt } from "@entro314labs/entro-auth/oauth2/dpop-client";
authorizationUrl.searchParams.set("dpop_jkt", await deriveDpopKeyJkt(keyPair));To send requests your own way, use the building blocks createDpopFetch uses:
await createDpopProof({ keyPair, method, url, accessToken, nonce })returns a proof for theDPoPheader.await isDpopNonceChallenge(response)tells whether a response asks for a retry with the nonce in itsDPoP-Nonceheader.createDpopNonceCache()keeps the latest nonce for each origin. Pass your own{ get, set }object asnonceCacheto keep nonces somewhere else, such as IndexedDB.
To send requests with another fetch implementation, pass it as fetch. createDpopFetch calls it as a plain function, so bind a method first, such as env.SERVICE.fetch.bind(env.SERVICE) for a Cloudflare service binding.
Server-provided nonces
A DPoP proof carries the time it was created, iat, but the client chooses that time. A client that holds the key can sign proofs for future use and copy them to a machine that lacks the key (RFC 9449 §11.2). A server-provided nonce stops this. Each proof must carry a recent value that only the server can create.
To require nonces, set dpop.nonce.required:
oauthProvider({
dpop: {
nonce: {
required: true,
expiresIn: 300, // 5 minutes, in seconds (the default)
},
},
})The token endpoint and the UserInfo endpoint then require a nonce in every DPoP proof:
- The client sends a proof without a nonce, or with an expired one.
- The endpoint rejects it with
use_dpop_nonceand sends a fresh nonce in theDPoP-Nonceresponse header. The token endpoint answers with a 400 (§8). The UserInfo endpoint answers with a 401 and aWWW-Authenticate: DPoP error="use_dpop_nonce"challenge (§9). - The client signs a new proof that includes the nonce, and retries.
The token endpoint checks the nonce before it redeems an authorization code, device code, or refresh token. The retry can therefore still redeem the same code. The endpoint measures nonce freshness at the time the request arrived. A nonce that expires while the grant runs does not fail the request.
Every successful DPoP response carries the next nonce in DPoP-Nonce (§8.2). A client that keeps the latest value rarely needs a retry. Responses that carry a nonce have these headers:
Cache-Control: no-store, so that a cache cannot hand out an expired nonce.DPoP-NonceinAccess-Control-Expose-Headers, so that browser clients can read it. The UserInfo challenge also listsWWW-Authenticate, which a browser client needs to see that it must retry.
Requests without a DPoP proof are unaffected.
Nonces are not stored. Each nonce holds its issue time and a signature keyed from your auth secret. Any instance with the same secret accepts a nonce another instance issued. Rotating the secret invalidates outstanding nonces, and each client recovers with one retry. Discovery metadata does not change, because RFC 9449 defines no metadata for nonces. A client learns that nonces are required from the first use_dpop_nonce response.
The OpenID4VC High Assurance Interoperability Profile 1.0 requires DPoP, and requires wallets to handle DPoP-Nonce from the authorization server and the credential issuer. To serve nonces from a plugin endpoint on the auth server, see Nonces on your own endpoints. For an API that verifies access tokens, see Require DPoP nonces.
Nonces on your own endpoints
A plugin endpoint on the auth server can verify DPoP proofs with the same rules as the token endpoint, nonces included. Call verifyDpopProof on the provider API:
import { getOAuthProviderApi } from "@entro314labs/entro-auth-oauth-provider";
import { createAuthEndpoint } from "@entro314labs/entro-auth/api";
import type { EntroAuthPlugin } from "@entro314labs/entro-auth/types";
export const dpopBinding = () =>
({
id: "dpop-binding",
endpoints: {
bindKey: createAuthEndpoint(
"/dpop/bind",
{ method: "POST" },
async (ctx) => {
const provider = getOAuthProviderApi(
ctx,
ctx.context.getPlugin("oauth-provider")!.options,
);
const proof = await provider.verifyDpopProof({ required: true });
// proof.jkt is the thumbprint of the key the client proved.
return ctx.json({ jkt: proof.jkt });
},
),
},
}) satisfies EntroAuthPlugin;verifyDpopProof checks the proof against your dpop settings and stores its jti, so the proof cannot be reused. Without required: true, it returns undefined when the request has no proof. When dpop.nonce.required is on:
- A proof without a current nonce fails with a 400
use_dpop_nonceerror and a freshDPoP-Nonce. - A verified proof sets the client's next nonce on the response.
Call it before your endpoint consumes a one-time credential, such as a code. The client's retry with the nonce can then still redeem it. When you call issueTokens or resolveConfirmation without a confirmation, let that method verify the proof. Verifying it twice rejects its jti as reused. A supplied confirmation replaces the proof for those methods. A proof sent through auth.api fails, because there is no HTTP method to check against htm.
An endpoint that only hands out nonces, such as a credential issuer's Nonce Endpoint, calls provider.issueDpopNonce(). It sets a nonce only when dpop.nonce.required is on. Otherwise it returns undefined and sets no header.
A plugin endpoint or before hook that stages state before the proof is verified calls provider.challengeDpopNonce() first. It sends the token endpoint's nonce challenge, a 400 use_dpop_nonce error with a fresh DPoP-Nonce, when the proof lacks a current nonce. The client's retry then finds the state untouched. It does nothing when dpop.nonce.required is off or the request has no DPoP header.
import { getOAuthProviderApi } from "@entro314labs/entro-auth-oauth-provider";
import { createAuthMiddleware } from "@entro314labs/entro-auth/api";
export const before = createAuthMiddleware(async (ctx) => {
if (ctx.path !== "/oauth2/token") return;
await getOAuthProviderApi(
ctx,
ctx.context.getPlugin("oauth-provider")!.options,
).challengeDpopNonce();
// Stage state here. The token endpoint verifies the proof afterwards.
});challengeDpopNonce checks only the proof's nonce. It does not verify the signature, htm, or htu, and it does not store the jti. The request must still verify the proof before you trust it. verifyDpopProof always verifies it. issueTokens and resolveConfirmation verify it only when no client-authentication confirmation is passed, because a confirmation replaces the proof. Within one request, that verification measures nonce freshness at the same time as the challenge, so a nonce that passes the challenge cannot expire before the proof is verified.
Bind later requests to a DPoP key
Some plugin endpoints take several requests to finish, such as a sign-in that returns a session handle the client sends back on its next request. Anyone who obtains the handle could continue the flow. To stop this, require every later request to carry a proof from the key that started it. Store the jkt that verifyDpopProof returned on the first request, and pass it as expectedJkt on each later one:
// First request: store proof.jkt with the handle you return.
const proof = await provider.verifyDpopProof({ required: true });
// Later request: require a proof signed with the same key.
await provider.verifyDpopProof({ expectedJkt: pending.dpopJkt });With expectedJkt, the request must carry a proof signed with that key, even without required: true. A missing proof, or a proof signed with another key, fails with invalid_dpop_proof. With dpop.nonce.required, a proof from the expected key without a current nonce gets use_dpop_nonce, so the client can retry. When expectedJkt is undefined, the call behaves as if you had not passed it.
On the request that issues the code with issueAuthorizationCode, set dpop_jkt in query to the stored key. The method checks a proof on the request against that key. If your endpoint already called verifyDpopProof on this request, the method reuses that result instead of verifying the proof again. The verified key binds the code, and a dpop_jkt in query must match it. A request without a proof still gets a code bound to the stored key, so only a token request with a proof from that key can redeem it.
Refuse token issuance
Some deployments must refuse tokens for a grant that is otherwise valid, for example when the user's sign-in does not meet a required assurance level or a device check fails. To refuse issuance, set beforeTokenIssuance. The provider calls it once for each token request, for every grant: authorization code, refresh token, client credentials, and every extension grant that calls issueTokens, such as the device code, CIBA, and token exchange grants. A refresh request replayed within refreshTokenReuseInterval gets the earlier response again, without a new call.
To let the request continue, return. To refuse it, throw an APIError with an OAuth error. The token endpoint returns that error unchanged and stores no token:
import { APIError } from "@entro314labs/entro-auth/api";
oauthProvider({
beforeTokenIssuance: ({ user, acr, scopes }) => {
if (user && scopes.includes("payments") && acr !== "urn:example:loa:2") {
throw new APIError("BAD_REQUEST", {
error: "invalid_grant",
error_description: "this scope requires a stronger sign-in",
});
}
},
})Use invalid_grant (RFC 6749 §5.2) unless the grant defines a better error. Authorization code and refresh token clients generally need a new authorization after invalid_grant. Other grants have their own recovery behavior. The CIBA grant also defines access_denied (CIBA Core §11), which tells the client the user denied the request.
The callback receives the issuance as one object:
grantType,client, anduser.useris undefined for client credentials.scopesandresources: what the tokens will carry, after resource narrowing.referenceId,sessionId,authTime,acr, andamrfrom the grant.actfor a delegated issuance, and theauthorizationDetailsthis issuance carries.confirmation: the key the tokens will be bound to, such as{ jkt }for DPoP. Undefined for bearer tokens.grantId.verificationValue: for the authorization code grant, the stored authorization request, including custom parameters inquery.grantRequest: the stored request an extension grant redeems, such as the approved device code. Its shape belongs to the grant.ctx: the token request's endpoint context.ctx.requestis undefined when your server calls the token endpoint throughauth.api.
Each callback gets its own copy of every value except ctx, client, and user. Changing a copy changes neither the tokens nor what a later callback receives. ctx, client, and user are the provider's own objects, so read them and do not change them.
The callback runs after the provider validates the grant and resolves the DPoP binding, and before any issuance-time claim callback, customTokenResponseFields, or token write. A refusal therefore has these effects:
- An authorization code is already used up, so the client must start a new authorization.
- A device code or CIBA request is used up only after the callback accepts the request, so a refusal leaves it approved and the client can poll again. An error thrown after the callback accepts, such as from a later claim callback, can use the request up, and the client must start over.
- A device-flow client stops polling after any error other than
authorization_pendingorslow_down(RFC 8628 §3.5), so the approved request then expires unused. - A CIBA client treats
invalid_request,access_denied,expired_token, andinvalid_grantas final and must not make further requests for the sameauth_req_id(CIBA Core §11). It may retry after a503with aRetry-Afterheader (CIBA Core §10.1). AbeforeTokenIssuancerefusal that throws such a response keeps the request redeemable. A503thrown by a later claim or response callback does not, because the request is already used up.
- A device-flow client stops polling after any error other than
- A refused refresh does not rotate the refresh token, so the client can present it again.
- A verified DPoP proof sent with the request is already used, so a retry needs a new proof. When client authentication supplies a
confirmation, it replaces the request's proof, and that proof is not used.
A provider extension can add the same check with its own beforeTokenIssuance. Each extension's callback runs in registration order, then the option's. The first one that throws refuses the issuance. Token exchange runs allowExchange first.
Custom claims
To add claims to access tokens, set customAccessTokenClaims. It receives user, scopes, referenceId, resources, the client's metadata, and the grantId when the issuance has one. It returns an object of claims to add. Use namespaced claim names, and see RFC 9068 §2.2 for the claims the provider already sets. To stop a token from being issued, for example when the user has left the organization, use beforeTokenIssuance instead of throwing here. For an opaque access token, this callback runs at introspection, not at issuance.
oauthProvider({
customAccessTokenClaims: ({ user, scopes, referenceId, resources }) => ({
"https://example.com/org": referenceId,
"https://example.com/roles": ["editor"],
}),
})For ID token and UserInfo claims, see OpenID Connect.
Client-specific access token claims
customAccessTokenClaims receives only the client's metadata. To base a claim on the full client record, add an extensions[].claims.accessToken contributor. It receives the full client record, user, scopes, referenceId, resources, grantId, and the client's metadata. When a JWT access token is minted, it also receives grantType, and sessionId for a session-backed grant. It returns an object of claims to add:
oauthProvider({
extensions: [{
claims: {
accessToken: ({ client }) =>
client.referenceId ? { "https://example.com/org": client.referenceId } : {},
},
}],
})client.referenceId is the client's owner, set by clientReference. It differs from the top-level referenceId, which is the consent reference from postLogin.consentReferenceId. Opaque-token introspection re-runs contributors without grantType or sessionId, so base the claim on the client, scopes, and resources. When names collide, see Claim precedence.
A JWT keeps its claims until it expires. An organization claim does not prove the client is still enabled. If your resource server must react to a disabled client right away, it should introspect the token. Introspection reports tokens of disabled clients as inactive.
Consent reference claim
When postLogin.consentReferenceId returns a consent reference, customAccessTokenClaims receives it as referenceId. The provider also puts it in the access token as the reference_id claim, and introspection returns it for opaque access tokens and refresh tokens. The provider owns this claim, so a claim contributor cannot set or override it.
Token exchange uses the claim to keep the reference on exchanged tokens. Resource servers can read it too, but a claim you derive in customAccessTokenClaims keeps your own name and shape.
Per-authorization grant ID
A user who signs in to the same client twice under one stored consent gets the same referenceId both times. To keep state for one authorization, such as data you release only once, key it on grantId instead. Every claim callback and customTokenResponseFields receives it.
grantId identifies one authorization:
- Each authorization code gets its own
grantId, so two sign-ins under one consent get different values. - A refresh keeps the
grantIdof the authorization it came from, through every rotation. - Any other grant that issues a refresh token, such as a device code with
offline_access, starts a newgrantId. - An issuance with no authorization code and no refresh token has none, such as client credentials. The callbacks then receive
undefined.
oauthProvider({
customAccessTokenClaims: async ({ grantId }) => {
const release = grantId ? await findIdentityRelease(grantId) : null; // your own lookup
return release ? { "https://example.com/verified": release.level } : {};
},
})Introspection of an opaque access token passes the same grantId that issuance did, so the claims it re-derives match. A JWT access token carries the value as the grant_id claim only when revocableJwtAccessTokens is on. Without that option, UserInfo cannot tell which grant a JWT access token came from, and customUserInfoClaims receives no grantId for it.
Custom token response fields
To add fields to the token endpoint's JSON response, set customTokenResponseFields. It receives grantType, user, scopes, the client's metadata, and the grantId when the issuance has one. For the authorization_code grant, it also receives verificationValue, which holds the original authorization request (query), the consent referenceId, and the sessionId. For a code that a plugin endpoint issued, verificationValue also holds the endpoint's serverContext. It returns an object of fields to add. The fields go in the response, not in the token itself. The provider replaces the standard fields, such as access_token and scope, with its own values. issued_token_type and authorization_details are reserved too, but this option does not remove them, so do not return them. See Token response fields. It runs after beforeTokenIssuance, and before any token is created. A provider extension can add fields with its own tokenResponseFields, and this option overrides a field an extension adds.
oauthProvider({
customTokenResponseFields: ({ grantType, verificationValue }) =>
grantType === "authorization_code" && verificationValue?.referenceId
? { tenant_id: verificationValue.referenceId }
: {},
})Revocation
POST /oauth2/revoke implements RFC 7009 §2.1. It applies these request rules:
- A parameter sent more than once returns 400
invalid_request. An empty value counts as omitted. - An unknown, expired, or already revoked token returns 200 instead of an error (RFC 7009 §2.2).
token_type_hintonly sets which token type is checked first. A token sent with the wrong hint is still revoked.
A client can only revoke tokens issued to it (RFC 7009 §2.1):
- A confidential client that sends another client's token gets 400
invalid_request. - A public client gets 200 and the token stays valid, so a public client can't use the endpoint to test whether a token exists.
What the endpoint does depends on the token:
- Opaque access token: deleted. Refresh tokens from the same grant stay valid.
- Refresh token: marked revoked, so it can no longer issue tokens. A refresh of the same grant that is still issuing tokens fails with
invalid_grant. The opaque access tokens of its grant are deleted, including those issued before earlier rotations (RFC 7009 §2.1). An opaque access token issued before your deployment stored grant IDs is deleted only with the refresh token that issued it. JWT access tokens from the same grant are revoked only withrevocableJwtAccessTokens. Without it, they stay valid until they expire. - Refresh token that was already revoked or rotated: treated as replay. The endpoint still returns 200, and it revokes the token's grant: its refresh tokens are deleted, along with the opaque access tokens they issued. The user's other grants with the client stay valid. A token rotated before your upgrade to 1.8 has no grant ID, so it deletes every refresh token the client holds for that user. With
revocableJwtAccessTokens, the JWT access tokens of the replayed token's grant are also revoked. Any other JWT access token, and an access token issued without a refresh token, stays valid until it expires. - JWT access token: revoked only with
revocableJwtAccessTokens. Without it, a JWT issued to the calling client that still verifies returns 400unsupported_token_type(RFC 7009 §2.2.1), because the token is never stored. An expired JWT is treated as unknown and returns 200. So does a JWT whose audience names a resource that is not registered.
To limit a JWT access token, keep accessTokenExpiresIn short or end the user's session. A JWT that carries a sid is reported inactive by introspection and rejected by UserInfo once its session ends. A client_credentials JWT has no session. Its lifetime is the only limit.
Grant revocation entries
A grant is revoked when a client revokes a refresh token, replays a rotated refresh token, or reuses an authorization code. It is also revoked when the user deletes the consent it was issued under, or resets their password while emailAndPassword.revokeSessionsOnPasswordReset is on and revokeGrantsOnPasswordReset is not false. The provider then writes one entry for the grant to the verification store, whatever your options. The entry lasts accessTokenExpiresIn, plus one second. With a function, it lasts accessTokenMaxExpiresIn, plus one second, instead.
A refresh token issued before 1.8 gets a grant ID at its first refresh after the upgrade. Revoking it before then, or replaying a token that was rotated before the upgrade, writes no entry, so a request still issuing tokens for that grant isn't stopped.
Each authorization code redemption and each refresh looks up its grant's entry after it stores its tokens. A request that finds the entry fails with invalid_grant and deletes the tokens it stored. This is how a revocation stops a request that was already issuing tokens for the grant. A request that reaches the lookup more than accessTokenExpiresIn (accessTokenMaxExpiresIn for a function) after it consumed its code or refresh token fails the same way, because the grant's entry may already have expired.
These entries are ordinary verification values:
- Your verification hooks see them.
databaseHooks.verificationruns for each entry the provider writes. The identifier starts withoauth-revoked-grant:, unlessverification.storeIdentifierhashes it. To act on revocations, useonTokenRevokedinstead of these entries. - A hook that vetoes an entry fails the revocation. If
verification.create.beforereturnsfalsefor a grant entry, the request that revoked the grant fails with 500server_error, andonTokenRevokedis not called. Revoking a refresh token or deleting a consent then leaves the token or consent in place, so the request can be retried. A replay of a refresh token or an authorization code, and a password reset, still delete the grant's stored tokens, but its JWT access tokens stay valid until they expire. - Reads must see earlier writes. If your verification store reads from a replica that lags behind writes, a request can miss an entry written moments earlier and keep its tokens.
- Secondary storage holds them if you use it. The entries go there and expire on their own. If the storage drops an entry before it expires, a request that was issuing tokens when the grant was revoked can keep them.
- Writes are bounded by the rate limit. Each grant revocation writes one entry. When rate limiting is enabled, which is the default in production, the rate limits bound how fast entries are written: 30 requests per 60 seconds for
/oauth2/revoke, and 20 for/oauth2/token. If you turn rate limiting off, nothing bounds them. Deleting a consent throughdeleteOAuthConsenthas no limit of its own and writes one entry for each grant of the consent.
Revoke JWT access tokens
A JWT access token is self-contained, so by default it stays valid until it expires. Set revocableJwtAccessTokens: true to let a client revoke one:
oauthProvider({
revocableJwtAccessTokens: true,
})Revoking a JWT access token then returns 200 and stores its jti in the verification store until the token's exp. After that, the token is reported inactive by introspection, rejected by UserInfo with 401 invalid_token, and reported inactive by validateAccessToken. Revoking the same token again returns 200.
If a verification.create.before hook returns false for the entry, whose identifier starts with oauth-revoked-access-token: unless verification.storeIdentifier hashes it, the revocation fails with 500 server_error, the token stays valid, and onTokenRevoked is not called.
Before you turn it on, consider:
- Resource servers that verify locally don't see revocations.
verifyAccessTokenRequestwithoutremoteVerify, andrequireMcpAuthwith ajwksUrl, check the signature against the JWKS and never ask the server. A revoked token stays valid there until it expires. To honor revocation, setremoteVerifyonverifyAccessTokenRequestso every token is introspected, and leavejwksUrlunset onrequireMcpAuthso it checks the provider's records in the same process. To pass revocations to other resource servers yourself, see Observe revocations. - Each check adds lookups. Introspection, UserInfo, and
validateAccessTokenlook up the token'sjtiin the verification store, revoked or not. A token that carries agrant_idalso has its grant looked up, in parallel. In the database, a lookup that finds an expired row also deletes the expired rows for that identifier. At most once a minute per server instance, a lookup also deletes every expired verification row.verification.disableCleanupturns off both deletes. Withverification.storeIdentifier: "hashed", each lookup that finds nothing takes two reads. - Revocations last only as long as their storage. With secondary storage, entries go there and expire on their own: a token's entry at its
exp, a grant's entry afteraccessTokenExpiresIn, oraccessTokenMaxExpiresInwhen that is a function. If the storage evicts or loses an entry, the revoked token is accepted again. Use storage that never evicts these keys, or setverification.storeInDatabase: trueto also keep entries in the database. - Writes are bounded by the rate limit. Revoking a JWT access token writes one entry, and only for a valid token issued to the calling client. When rate limiting is enabled, which is the default in production, the rate limits bound how fast entries are written: 30 requests per 60 seconds for
/oauth2/revoke. If you turn rate limiting off, nothing bounds them. Grant revocations write their own entries, with or without this option.
Revoke the access tokens of a grant
A grant is everything one authorization produced: its first tokens and every refresh token rotated from them. Each refresh token stores its grant's ID. With the option on, each JWT access token issued with a refresh token or for an authorization code also carries it in a grant_id claim. Entro Auth sets this claim, and custom access-token claims can't override it.
Revoking a refresh token then also revokes the JWT access tokens of its grant, including those issued before earlier rotations (RFC 7009 §2.1). Entro Auth checks each token against the grant revocation entry, so it stores one entry for the grant, not one per token. The entry lasts accessTokenExpiresIn, or accessTokenMaxExpiresIn when that is a function, and every access token the grant issued before the revocation expires within that time. The same happens in these cases:
- A refresh token that was already rotated is presented for revocation, or at the token endpoint outside the
refreshTokenReuseIntervalwindow. A retry inside that window gets the earlier response back and revokes nothing. - An authorization code is reused by the client it was issued to, and the request passes the checks in Authorization code reuse. The code's grant is revoked, including a JWT access token issued for the code without a refresh token. This holds even when the reuse arrives while the first redemption is still issuing its tokens.
- The user deletes the consent the grant was issued under, and the grant has a refresh token or a stored opaque access token that carries its ID. See Revoke tokens with a consent.
- The user resets their password with
emailAndPassword.revokeSessionsOnPasswordReseton andrevokeGrantsOnPasswordResetnotfalse, and the grant has a refresh token or a stored opaque access token that carries its ID. See Password reset.
The grant revocation has these limits:
- Other grants stay valid. A replayed refresh token revokes its own grant and no other. The user's other grants with that client keep their refresh tokens, opaque access tokens, and JWT access tokens. A replayed authorization code deletes only the tokens issued for that code. A replayed token that was rotated before you upgraded to 1.8 is the exception, because it has no grant ID. It deletes every refresh token the client holds for that user, and the opaque access tokens linked to them, but revokes no JWT access token. In a grant that a device code or a CIBA request started, the opaque access tokens of tokens rotated before the upgrade stay valid until they expire, because nothing links them to the grant.
- Most tokens without a refresh token aren't covered. A JWT access token issued without a refresh token has a
grant_idonly when it was issued for an authorization code, and only a reuse of that code revokes it. Revoke any other such token by itsjti, or end the user's session. - Tokens from token exchange aren't covered. A token that a client obtained by exchanging one of the grant's access tokens doesn't carry the grant's
grant_id. It stays valid until it expires. - Tokens from before you turned the option on aren't covered. They carry no
grant_id. JWT access tokens issued from then on carry it, including those issued by refreshing an earlier refresh token. - Shortening the lifetime shortens the entry. If you lower
accessTokenExpiresIn, oraccessTokenMaxExpiresInfor a function, a token issued under the longer lifetime can outlive the entry for its grant.
Revoke tokens with a consent
Deleting a consent through deleteOAuthConsent revokes the tokens issued under it: the access and refresh tokens stored for that user, that client, and the consent's reference. Tokens of the same user and client under another reference stay valid, and so do tokens of other users and clients.
- Refresh tokens and their grants. Each grant of the consent is revoked before its tokens are deleted. A refresh of the grant that is still issuing tokens fails with
invalid_grant. WithrevocableJwtAccessTokens, the grant's JWT access tokens are revoked too. - Opaque access tokens. They are deleted, including one issued without a refresh token.
- JWT access tokens. Without
revocableJwtAccessTokens, they stay valid until they expire. A JWT issued without a refresh token has no stored record to find, so it also stays valid until it expires, or until the user's session ends when it carries asid. - Rows from before 1.8. A refresh token stored without a grant ID is deleted by the consent's scope, but a refresh that was already issuing tokens for it isn't stopped.
- Pending authorization codes, approved device codes, and CIBA requests approved from the link. They can no longer be redeemed. Redeeming one fails with
invalid_grant, because redemption checks the consent. A consent given again for the same client, consent reference, and access makes them redeemable again. Those of a client withskip_consentare not checked. - CIBA requests approved with
completeCibaRequest. A CIBA request approved this way stores no consent. It can still be redeemed until it expires, 300 seconds by default. - A redemption in flight. An authorization code, device code, or CIBA redemption that passed its consent check just before the consent is deleted has stored nothing to revoke, so it can still finish, and the tokens it issues stay valid.
- A failed revocation keeps the consent. The call fails and the consent stays in place, so the user can delete it again.
Observe revocations
A resource server that verifies JWT access tokens against the JWKS never asks the provider, so it accepts a revoked token until the token expires. To tell such a server about each revocation, or to keep an audit log, set onTokenRevoked:
oauthProvider({
revocableJwtAccessTokens: true,
onTokenRevoked: async (event) => {
if (event.type === "access_token") {
// An opaque access token has no jti, and resource servers must introspect it anyway.
if (event.jti) await revokedTokens.add(event.jti, event.expiresAt);
} else if (event.grantId) {
await revokedGrants.add(event.grantId, event.expiresAt);
}
},
});revokedTokens and revokedGrants stand for your own storage. A resource server that reads them rejects a JWT access token whose jti or grant_id it finds there.
The provider reports a revoked grant, or a single revoked access token. A refresh token and an authorization code each stand for their grant, so revoking one revokes the grant's opaque access tokens, and its JWT access tokens too with revocableJwtAccessTokens. The event names the grant for authorization codes and refresh tokens with a grant ID; a refresh token stored before 1.8 may have no grantId. Revoking it directly reaches its linked access tokens. Reuse of a legacy token without a grant ID has the broader effect described below. A client revokes an access token on its own, so the event names that token.
The provider calls onTokenRevoked after it revokes tokens, with an event that has these fields:
type: the token the request presented,"access_token","refresh_token", or"authorization_code".reason: why the provider revoked the tokens."revocation_request": the client revoked the token at/oauth2/revoke. This includes revoking a refresh token again after a revocation or a session end already revoked it."reuse_detected": a client refreshed with a rotated or revoked refresh token, asked to revoke a rotated refresh token, or redeemed an authorization code again. Reuse can indicate token theft. A legitimate client retrying after a lost refresh response can produce the same event, so confirming theft requires other evidence.
clientId: the client the tokens were issued to.jti: thejtiof a revoked JWT access token. An opaque access token has none.grantId: for a refresh token or an authorization code, the grant whose access tokens were revoked. WithrevocableJwtAccessTokens, JWT access tokens carry it asgrant_id. A refresh token stored before 1.8 has none until its first refresh after the upgrade.userId: for a refresh token, the user it was issued to.expiresAt: no access token the revocation covers is accepted after this time. Keep your record of the revocation until then. If you shorten the configured lifetime or its per-grant ceiling (accessTokenMaxExpiresIn), a token issued earlier can outlive this time, so keep the record until the longest-lived affected token expires.ctx: the endpoint context of the request. Its body and headers hold the presented token and the client's credentials. Record the other fields of the event, notctx.
Revocation and Revoke the access tokens of a grant describe which tokens each request revokes. A "revocation_request" for a refresh token revokes as much as a reuse does in two cases:
- The refresh token was already revoked.
- A refresh of the same token races the revocation.
Revocations it does not report
The callback reports only what the provider revoked. It isn't called for an unknown, expired, or already revoked access token, for a token issued to another client, or for an authorization code reused by another client or without its code_verifier. It isn't called for a refresh that rotates the refresh token either, because the grant stays valid. Inside the reuse interval, a rotated refresh token presented to the token endpoint revokes nothing.
Tokens also stop working for the causes below. None of them reaches the callback, so a resource server that depends on one needs another way to learn of it:
- An ended session. Ending a session revokes the access tokens issued for it, and its refresh tokens unless they grant
offline_access. From then on, introspection and UserInfo also reject a JWT access token that carries the session'ssid. To learn when a session ends, usedatabaseHooks.session.delete.after. A refresh with a session-bound token after its session ends returnsinvalid_grant, leaves other grants alone, and emits no event. Explicitly revoking that token at/oauth2/revokecan still emit"revocation_request". - A disabled client. Introspection reports the client's tokens as inactive. Nothing is revoked, and a JWT access token that a resource server verifies locally stays valid until it expires.
- A deleted client or user. Introspection reports a deleted client's tokens as inactive. A database that enforces the schema's foreign keys also deletes the tokens of a deleted client or user. The provider doesn't see the delete.
- A deleted resource. Introspection reports the tokens issued for the resource as inactive.
- A deleted consent. Deleting consent revokes the stored grants for the client, user, and consent reference. The provider sends no callback for these grants. See Revoke tokens with a consent.
- A password reset. A reset that revokes a user’s stored grants sends no token-revocation callback. See Password reset.
- Legacy refresh tokens without a grant ID. Reusing one can delete other refresh tokens of the same client and user and their linked opaque access tokens. No grant ID is available to name those grants in the event. With a grant ID, replay revokes only the presented token’s grant.
Delivery is best effort
The provider reports a revocation after it has happened, and it doesn't retry. Before you rely on it, consider:
- The response waits for it. The provider awaits the callback before it answers the request, so keep it fast.
- A failed callback loses the event. The tokens are already revoked when the callback runs. An error it throws is logged, and the response stays the same, so the client does not retry. A resource server that relies on your record then accepts the token until it expires. A resource server that must never accept a revoked token should introspect every token instead, with
remoteVerify. - A failed request can go unreported. If a database write fails partway through a revocation, the request fails with an error. Tokens revoked before the failure stay revoked, and the callback is not called for them.
- A cleanup failure doesn't stop the report. If deleting the tokens of a reused authorization code fails, the provider logs the failure and still calls the callback. The grant's entry is already written, but an opaque access token that wasn't deleted stays valid until it expires.
- An event can arrive more than once. Concurrent requests that revoke the same token can each report it. Key your records by
jtiorgrantId.
Without the JWT plugin
To run without the JWT plugin, set disableJwtPlugin: true:
- Access tokens are always opaque, even when a
resourceis requested. The requested resources are still bound to the token and returned by introspection. - ID tokens are signed with HS256 using the client secret. Public clients have no secret and get no ID token. They can still call UserInfo with the access token.
storeClientSecretdefaults to"encrypted", since the secret must be readable to sign ID tokens.
oauthProvider({
disableJwtPlugin: true,
})Storage
By default, your database stores opaque access tokens and refresh tokens as hashes. Client secrets are hashed with the JWT plugin and encrypted without it.
storeClientSecret:"hashed"or{ hash, verify? }with the JWT plugin;"encrypted"or{ encrypt, decrypt }without it. The provider fails to start on any other combination.storeTokens:"hashed"or{ hash: (token, type) => string }.
To make issued values recognizable to secret scanners, set prefix:
oauthProvider({
prefix: {
opaqueAccessToken: "myapp_at_",
refreshToken: "myapp_rt_",
clientSecret: "myapp_cs_",
},
})Set prefixes before your first production deployment and keep them fixed afterwards. To add a prefix to a provider that has already issued values, use generateOpaqueAccessToken, generateRefreshToken, or generateClientSecret instead.
Device code grant
To enable the device code grant (RFC 8628 §3.4) at /oauth2/token, add oauthDeviceAuthorization() next to oauthProvider(). See Device Authorization for setup.
The user approves a device code through /oauth2/authorize?user_code=…, on the same sign-in, account selection, post-login, and consent pages as an authorization request. See Approve the device. The integration adds the OAuth client, RFC 8707 resource, consent reference, authentication time, and authentication context (acr, amr) fields to the device code. Standalone Device Authorization installations are unchanged.
Token exchange
A service that receives a user's access token sometimes needs to call another API as that user. Forwarding the token fails the API's audience check and gives the API more access than it needs. Token exchange (RFC 8693) lets the service trade the token at the token endpoint for a new access token for the other API. The new token has the same user as sub, the downstream API as aud, and the exchanging service as client_id.
By default, the exchanged token impersonates the user: it represents the user and does not name the service. A typical case is an MCP server that receives a token for itself and calls a downstream API. To record that the service acts for the user, send an actor token. See Delegate to an actor.
Set up token exchange
Add oauthTokenExchange() after oauthProvider(). List the scopes the service uses in scopes. Then list both the resource the service receives tokens for and the resource it calls.
Disable the JWT plugin's /token endpoint and its set-auth-jwt header, as OAuth Provider Mode describes. Both give a signed-in user a session JWT, signed with the same keys as access tokens. By default, that JWT carries the auth server's URL as its issuer and audience. If either path stays enabled, a resource server that checks only signature, issuer, and audience can accept the session JWT as an access token. The example disables both:
import { entroAuth } from "@entro314labs/entro-auth";
import { jwt } from "@entro314labs/entro-auth/plugins";
import { oauthProvider, oauthTokenExchange } from "@entro314labs/entro-auth-oauth-provider";
export const auth = entroAuth({
disabledPaths: ["/token"],
plugins: [
jwt({ disableSettingJwtHeader: true }),
oauthProvider({
loginPage: "/sign-in",
consentPage: "/consent",
scopes: ["openid", "profile", "email", "offline_access", "read", "write"],
resources: ["https://mcp.example.com", "https://api.example.com"],
}),
oauthTokenExchange(),
],
});The grant urn:ietf:params:oauth:grant-type:token-exchange is then advertised in grant_types_supported. RFC 8693 defines no other discovery metadata.
Register the exchanging service as a confidential client with TOKEN_EXCHANGE_GRANT_TYPE. A public client can exchange only its own DPoP-bound tokens, and only after you enable public clients.
import { TOKEN_EXCHANGE_GRANT_TYPE } from "@entro314labs/entro-auth-oauth-provider";
await auth.api.adminCreateOAuthClient({
headers,
body: {
client_name: "MCP server",
grant_types: [TOKEN_EXCHANGE_GRANT_TYPE],
token_endpoint_auth_method: "client_secret_basic",
scope: "read write",
resources: ["https://mcp.example.com", "https://api.example.com"],
skip_consent: true,
},
});The client's linked resources do two jobs here:
- Linking
https://mcp.example.comlets the client exchange tokens whose audience is that resource, which are the tokens it receives. It can exchange them even when they are DPoP-bound to another client. See Exchange DPoP-bound tokens. - Linking
https://api.example.comlets the client request tokens for that resource.
skip_consent decides whether the user must have approved the exchanging client:
- With
skip_consent: true, which only an admin can set, the client may exchange any token it is allowed to receive. Use it for first-party services. - Otherwise, the user must already have a stored consent for this client that covers the requested scopes and resources, for example from an earlier authorization code flow with that client. Without one, the exchange fails with
invalid_request. A client created through dynamic registration cannot setskip_consent, so it can only reach what the user has already approved for it.
Exchange a token
The service sends the user's token as subject_token and names the target with resource:
curl https://auth.example.com/api/auth/oauth2/token \
-u "$EXCHANGING_CLIENT_ID:$EXCHANGING_CLIENT_SECRET" \
-d grant_type=urn:ietf:params:oauth:grant-type:token-exchange \
--data-urlencode "subject_token=$USER_ACCESS_TOKEN" \
-d subject_token_type=urn:ietf:params:oauth:token-type:access_token \
--data-urlencode resource=https://api.example.com \
-d scope=read{
"access_token": "eyJ...",
"issued_token_type": "urn:ietf:params:oauth:token-type:access_token",
"token_type": "Bearer",
"expires_in": 58,
"expires_at": 1767225658,
"scope": "read"
}| Parameter | Behavior |
|---|---|
subject_token | Required. An active access token this server issued |
subject_token_type | Required. Must be urn:ietf:params:oauth:token-type:access_token |
resource | Required unless audience is sent, and may repeat (RFC 8707). Each value must be a registered, enabled resource, linked to the client while enforcePerClientResources is on |
scope | Optional. Defaults to the subject token's scopes, without openid and offline_access, that the client is also registered for |
requested_token_type | Optional. Only urn:ietf:params:oauth:token-type:access_token is accepted |
actor_token, actor_token_type | Optional, sent together. See Delegate to an actor |
audience | Optional, and may repeat. Each value must equal a registered resource identifier and is treated like resource |
With the JWT plugin enabled, the exchanged token is a JWT access token whose aud is the requested resource. With disableJwtPlugin: true, or for a resource with opaque access tokens, it is opaque and the resource is returned by introspection. The response has no refresh token and no ID token.
Exchange as a public client
A public client, such as a desktop, mobile, or browser app, has no secret, so the provider cannot tell it apart from someone who copied its client_id. By default, a public client that requests a token exchange gets invalid_client. To let public clients exchange tokens, set publicClients to "dpop-bound":
oauthTokenExchange({
publicClients: "dpop-bound",
});A DPoP key (RFC 9449) held by the app then stands in for its secret. The provider accepts an exchange from a public client registered for the token-exchange grant only when all of these hold:
- The subject token was issued to that same client. A token whose audience the client is linked to is not enough.
- The subject token is DPoP-bound. Get one by sending a DPoP proof with the token request that redeems the authorization code, or any other way listed under DPoP.
- The request carries a DPoP proof from the subject token's key.
- The request has no
actor_token.
A public client cannot get a client_credentials token, so any actor token it sent would be a user's token issued to the same app. The provider does not support that form of delegation for public clients.
The exchanged token is bound to the same key. Someone who steals a public client's access token cannot exchange it without that key.
Confidential clients still authenticate as before.
Delegate to an actor
An impersonation token does not show which service acts for the user. A resource server then cannot tell a call from the user's own client apart from a call by a service in between. Delegation (RFC 8693 §1.1) adds that information. The service sends an actor token next to the subject token, and the exchanged token names the actor in its act claim. The token keeps the same user as sub, and the same scopes and audience rules as an impersonation token.
The actor token must be an access token this server issued to the exchanging client. A service usually sends its own client_credentials token:
curl https://auth.example.com/api/auth/oauth2/token \
-u "$EXCHANGING_CLIENT_ID:$EXCHANGING_CLIENT_SECRET" \
-d grant_type=urn:ietf:params:oauth:grant-type:token-exchange \
--data-urlencode "subject_token=$USER_ACCESS_TOKEN" \
-d subject_token_type=urn:ietf:params:oauth:token-type:access_token \
--data-urlencode "actor_token=$SERVICE_ACCESS_TOKEN" \
-d actor_token_type=urn:ietf:params:oauth:token-type:access_token \
--data-urlencode resource=https://api.example.comTo get that token, register the service for both grants, grant_types: [TOKEN_EXCHANGE_GRANT_TYPE, "client_credentials"], with the scopes it may request in client_credentials_scopes. The exchanged token then carries:
{
"sub": "user_123",
"client_id": "mcp-server",
"act": {
"sub": "mcp-server",
"sub_profile": "service"
}
}act.sub is the actor token's subject. For a client_credentials token, it is the client ID. For a user's token issued to the service, it is that user's ID. act.sub_profile names the actor's kind: "service" for a client and "user" for a user. Introspection returns act for JWT and opaque access tokens.
When the exchanged token's client uses pairwise subject identifiers, it can see each user in act as the sub it sees for that user, instead of the user ID. Where it sees those values depends on the token format:
- Introspection always returns those values.
- A JWT access token carries them with
accessTokenSubject: "pairwise". With the defaultaccessTokenSubject: "user", the JWT carries user IDs inact, as it does insub.
A service named in act keeps its client ID, because its entry is marked "service". That still holds after the service's client is deleted. A pairwise client sees an entry without sub_profile, such as one from a token delegated before the provider added it, as a user.
allowExchange, actorClaims, and the provider API receive user IDs.
Actor chains
A delegated token can be exchanged again. When the next service sends its own actor token, the new actor wraps the earlier one, as RFC 8693 §4.1 describes:
{
"act": {
"sub": "billing-service",
"sub_profile": "service",
"act": {
"sub": "mcp-server",
"sub_profile": "service"
}
}
}The outer act is the current actor. Nested entries are earlier actors, and RFC 8693 treats them as information only, not for access decisions.
An exchange never removes actors. When a delegated token is exchanged without an actor token, the exchanged token keeps the subject token's act unchanged. Otherwise, a service could turn a delegated token into an impersonation token.
delegation.maxDepth limits the number of actors in a chain. It defaults to 1, so a delegated token can be exchanged again only without a new actor. Raise it to allow chains, or set it to 0 to reject every actor token and every subject token that has act:
oauthTokenExchange({
delegation: { maxDepth: 2 },
});Delegation rules
The provider applies these rules to every delegation, in addition to the exchange rules:
| Rule | Why |
|---|---|
| The actor token is an active access token this server issued to the exchanging client | A client can only name an actor whose token was issued to it, not one that only lists the client in aud |
The actor token has no act of its own | Its earlier actors would be lost from the chain |
| The actor is not the subject token's user | A user acting for themselves adds nothing to the audit trail |
| An actor token bound to a key requires proof of that key | Someone who copies the actor token cannot use it without the key |
When the subject token has may_act, the request has an actor that matches it | The subject token decides who may act for its user |
The chain has at most maxDepth actors | Chains cannot grow without limit |
| The exchanged token expires no later than the actor token | Delegated access ends when the actor's token ends |
A token the client got by exchanging a user's token is also issued to the client, so it can be an actor token. A service that can exchange a user's token can already act as that user, so this gives it no access it did not have.
Limit who may act with may_act
A subject token with a may_act claim (RFC 8693 §4.4) names who may act for its user. The provider never adds may_act itself. Add it with customAccessTokenClaims, which also covers opaque tokens at introspection:
oauthProvider({
// ...
customAccessTokenClaims: ({ resources }) =>
resources?.includes("https://mcp.example.com")
? {
may_act: {
client_id: process.env.MCP_SERVER_CLIENT_ID,
sub_profile: "service",
},
}
: {},
}),Every member of may_act must match the actor:
submust equal the actor'sact.sub.sub_profilemust equal the actor's kind:"service"or"user".client_idmust equal the actor token's client, which is the exchanging client.issmust equal this server's issuer: the discoveryissuer, or thejwt.issuerorbaseURLit comes from, as you configured it.
In the example, client_id with sub_profile: "service" allows only the MCP server acting as itself, with its own client_credentials token. client_id alone also allows users whose actor tokens were issued to that client.
Any other member denies the exchange, because the provider cannot check it. A may_act without sub or client_id also denies it, because it names no one. That includes the example above when MCP_SERVER_CLIENT_ID is unset. A subject token with may_act also cannot be exchanged without an actor token.
To name a user actor, set sub to the user ID, never to a pairwise sub. The exchange compares the user ID.
When the subject token's client uses pairwise subject identifiers, the provider presents may_act.sub the way it presents users in act. The client then sees the sub it sees for that user, not the user ID:
- Introspection always returns that value.
- A JWT access token carries it with
accessTokenSubject: "pairwise". With the defaultaccessTokenSubject: "user", the JWT carries the user ID inmay_act, as it does insub.
The provider treats every sub as a user ID unless sub_profile is "service", and shows a "service" sub to every client unchanged. Use "service" only for client IDs. To name a service by sub instead of client_id, set sub_profile: "service". Otherwise, a pairwise client sees a value that matches no client ID.
Other may_act members, such as an email address, reach the client as you wrote them, even for a pairwise client. Do not put a user ID or another value that identifies a user in them.
Add fields to the actor
delegation.actorClaims adds your own fields to the current actor's entry in act. It runs after every other check, only when the request has an actor token. It receives the same request as allowExchange, with actor always set:
oauthTokenExchange({
delegation: {
actorClaims: ({ actor }) => ({
actor_issued_at: actor.token.iat,
}),
},
});The fields you return reach the token's client and its resource servers as you wrote them, even for a pairwise client. Do not return a user ID or another value that identifies a user to clients that should see only pairwise values.
The provider ignores the fields sub, sub_profile, iss, and act and logs a warning. The hook cannot change who acted, the actor's kind, or the earlier actors.
act belongs to the authorization server, like cnf. customAccessTokenClaims, claim contributors, and resource customClaims cannot set it.
Exchange DPoP-bound tokens
DPoP stops anyone without the client's private key from using a leaked token at your API, as long as the API verifies the proof. When the client the token was issued to exchanges it, the exchanged token stays bound to the same key. A service in the token's audience can also exchange it, without that key.
The exchange request decides how the exchanged token is bound:
- If the request carries a
DPoPproof, the exchanged token is bound to that key andtoken_typeisDPoP. - A proof is required when the exchanging client or the target resource requires DPoP-bound tokens. It is also required when a client exchanges its own DPoP-bound token.
- Otherwise, an exchange without a proof returns a bearer token.
A clientAuthentication strategy can prove a key itself and return it as confirmation. The exchanged token is then bound to that confirmation instead of a proof, and no DPoP proof is required.
When the subject token is DPoP-bound, the rules depend on who exchanges it:
- The client the token was issued to must prove the same key. It sends a proof signed by that key, as it does for a refresh, or its
clientAuthenticationstrategy returns that key asconfirmation. The exchanged token stays bound to that key. A request with neither a proof nor aconfirmationfails withinvalid_dpop_proof. So does a proof orconfirmationwith another key. - A service in the token's audience, such as the MCP server that received it, does not hold the client's key. If the service sends its own proof, the exchanged token is bound to the service's key. If it sends no proof and none is required, the exchanged token is a bearer token.
A subject token can also be bound by another mechanism, such as an mTLS certificate in cnf["x5t#S256"] that came from a strategy's confirmation. When the client the token was issued to exchanges it, its strategy must return the same confirmation again. The exchanged token then stays bound to that certificate. The exchange fails with invalid_request in any of these cases:
- The strategy returns a different certificate.
- The strategy returns no
confirmation. A DPoP proof does not replace it. - The token's
cnfuses a method the server does not recognize.
A service in the token's audience is treated as for a DPoP-bound token. The exchanged token is bound to the service's own proof or confirmation, or is a bearer token when the service sends neither and none is required.
An actor token is always the exchanging client's own token. When it is bound to a key, the request must prove the same key:
- For a DPoP-bound actor token, send a proof signed by that key, or let the client's
clientAuthenticationstrategy return that key asconfirmation. - For an actor token bound another way, such as to a certificate, the strategy must return the same
confirmation.
The exchanged token is then bound to that key.
A service that passes the exchange rules does not need the client's key. It can turn each DPoP-bound token it receives into a token for the APIs it is linked to. To keep those tokens DPoP-bound, require a proof in either of these ways:
- Register the service with
dpop_bound_access_tokens: true. Every token request from the service then needs a proof, including its exchanges. - Set
dpopBoundAccessTokensRequired: trueon the target resource. Every client then needs a proof to get tokens for that resource.
To refuse these exchanges instead, accept a sender-constrained subject token, such as a DPoP-bound one, only from the client it was issued to:
oauthTokenExchange({
allowExchange: ({ client, subjectToken }) =>
!subjectToken.cnf || subjectToken.client_id === client.clientId,
});A refused exchange fails with invalid_request.
Exchange rules
The provider applies these rules to every exchange, before your allowExchange policy:
| Rule | Why |
|---|---|
The client is registered for the token-exchange grant and is confidential, or is a public client allowed by publicClients | Someone who only holds a leaked token cannot exchange it |
| The subject token is an access token this server issued to a user | Tokens from other issuers and machine tokens from client_credentials are rejected |
The subject token carries no authorization_details | The exchanged token would drop the details the user approved, which the resource server must receive (RFC 9396 §9) |
| The client is the subject token's client, or is linked to a resource in the token's audience | A client cannot exchange a token that was never sent to it |
A client that exchanges its own sender-constrained token proves the same binding: the same DPoP key, or the same strategy confirmation | An exchange cannot remove or replace the client's binding |
The requested scopes are a subset of the subject token's scopes and the client's registered scopes. openid and offline_access are never exchanged | An exchange cannot add access. An exchange is not a sign-in |
Each target resource is registered and enabled, and linked to the client while enforcePerClientResources is on (the default) | The client's resource policy still applies, including each resource's allowedScopes |
| A client that does not skip consent needs a stored consent covering the scopes and resources | The user must have approved this client for this access |
The exchanged token expires no later than the subject token and carries the subject token's session (sid) | Repeated exchanges cannot extend access, and once the session ends, introspection reports exchanged tokens inactive |
| No refresh token or ID token is issued | The service must exchange again when the token expires |
Scope names are global across resources. A read scope on the MCP server and a read scope on the API are the same scope, so restrict what a resource accepts with its allowedScopes.
Token exchange errors
A token exchange fails with one of these errors:
invalid_request(400), when any of these applies:- The subject token is missing or invalid.
subject_token_typeis unsupported.- The request sends only one of
actor_tokenandactor_token_type. actor_token_typeis noturn:ietf:params:oauth:token-type:access_token.- The actor token is invalid, expired, or not issued to the client.
- The actor token represents the subject token's user.
- The actor token carries its own
act. - The actor token is bound to a key the request does not prove, by a binding other than DPoP.
- The subject token's
may_actnames no actor, does not match the actor, or the request has no actor. - The
actchain would exceeddelegation.maxDepth. requested_token_typeis unsupported.- The request sends neither
resourcenoraudience. - The user has no stored consent for the client that covers the request.
- The client exchanges its own token bound by a non-DPoP
cnf, such as an mTLS certificate, and its client authentication does not return that sameconfirmation. - Your
allowExchangepolicy denies the exchange. - A public client sends a subject token issued to another client, a subject token that is not DPoP-bound, or an
actor_token.
invalid_scope(400), when any of these applies:- The request names a scope that the subject token or the client does not have.
- The request names
openidoroffline_access. - A target resource's
allowedScopesallows none of the requested scopes.
invalid_target(400), when any of these applies:- A
resourceoraudiencevalue is unknown or disabled. - A
resourceoraudiencevalue is not linked to the client whileenforcePerClientResourcesis on. - A
resourceoraudiencevalue is the userinfo endpoint.
- A
invalid_client, when client authentication fails, including when a public client exchanges withoutpublicClients: "dpop-bound".unauthorized_client(400), when the client is not registered for the token-exchange grant.invalid_dpop_proof(400), when any of these applies:- The DPoP proof is invalid.
- A proof is required and the request has none.
- The client exchanges its own DPoP-bound token with a proof, or a strategy
confirmation, for another key. - A DPoP-bound actor token comes without a proof from its key, and the client's strategy
confirmationdoes not prove that key either. - The subject token and the actor token are both the client's own and are bound to different keys.
Keep the organization the user approved
When postLogin.consentReferenceId picks a reference during authorization, such as the organization the user approved, the exchanged token keeps the subject token's reference. It does not switch to the user's current active organization. customAccessTokenClaims receives the same referenceId, so a claim you derive from it carries over to the downstream API. A client that does not skip consent needs a stored consent under that same reference.
The provider reads the reference from the subject token's reference_id claim, so no extra configuration is needed. An exchange cannot change the organization. To act in another one, the user authorizes the client for that organization.
Add your own policy
allowExchange runs after every built-in rule passes. Return false to deny the exchange with invalid_request, or throw an APIError to return a different OAuth error. It receives:
client: the authenticated clientuser: the user the subject token representsresources: the requested resourcesscopes: the scopes the exchanged token will carry, after each resource'sallowedScopesnarrows the requested onesreferenceId: the inherited consent referencesubjectToken: the subject token's introspection payloadactor: the validated actor, when the request sends an actor token. It hassub, the actor'suserwhen the actor token represents a user, andtoken, the actor token's introspection payloadact: theactclaim the exchanged token will carry, before fields fromdelegation.actorClaims
allowExchange and delegation.actorClaims receive a copy of the request. Changing it does not change the exchanged token.
oauthTokenExchange({
allowExchange: ({ client, resources }) =>
client.clientId === process.env.MCP_SERVER_CLIENT_ID &&
resources.every((resource) => resource === "https://api.example.com"),
});To require delegation, so that every exchanged token names its actor, deny requests without one:
oauthTokenExchange({
allowExchange: ({ actor }) => actor !== undefined,
});Limitations
- Actor tokens are access tokens from this server. ID tokens and tokens from other issuers cannot be actor tokens.
- Revoking the actor. Revoking the actor token, or ending the actor user's session, does not revoke tokens exchanged with it earlier. They still expire no later than the actor token.
- No refresh tokens are issued for exchanged tokens.
- Own access tokens only. ID tokens, refresh tokens, and tokens from other issuers cannot be exchanged.
- Signing out and local JWT verification. Signing out makes exchanged tokens inactive at introspection. A resource server that verifies JWT access tokens locally against the JWKS keeps accepting them until
exp, which is never later than the subject token'sexp. - Subject tokens without a session. An access token refreshed from an
offline_accessrefresh token after the user signed out carries nosid. A token exchanged from it is not tied to a session and lasts until itsexp. ReturnfalsefromallowExchangewhensubjectToken.sidis missing if exchanges must always end with the session. - Pairwise subjects. The exchanged token belongs to the exchanging service, so introspection reports that service's
subfor the user. A service that exchanges a pairwise client's token can link that client'ssubto its own. - Registration default resources.
clientRegistrationDefaultResourceslinks every dynamically registered client to those resources. Such a client then counts as a resource server for tokens whose audience is one of them, so the audience rule does not tell it apart from your own service. The consent rule still limits it to what the user approved for that client.