You are currently viewing documentation for v1.8 (Beta)
OAuth Provider reference
OAuth provider options, endpoints, errors, rate limits, extensions, and database schema.
Plugin options
Pass these options to oauthProvider(). Only loginPage and consentPage are required.
Sign-in flow
loginPage string
Required. Page the authorize endpoint redirects to when the user must sign in. See Login page.
consentPage string
Required. Page the authorize endpoint redirects to when the user must consent. See Consent page.
signup object
Settings for prompt=create. See Sign-up account screen.
selectAccount object
Settings for prompt=select_account. See Select account screen.
postLogin object
A step between login and consent, such as choosing an organization. See Post-login screen.
allowPublicClientPrelogin boolean
Lets /oauth2/public-client-prelogin answer before sign-in when the request carries a valid signed oauth_query. The requested client_id must match the client in the signed query. Defaults to false.
Scopes and claims
scopes string[]
Scopes clients may request. Without openid, the provider is OAuth only. Defaults to ["openid", "profile", "email", "offline_access"]. See Scopes.
advertisedMetadata { scopes_supported?, claims_supported? }
Overrides what discovery advertises. Every scopes_supported value must be in scopes. See Discovery metadata.
customAccessTokenClaims (info) => Awaitable<Record<string, any>>
Adds access token claims, also returned by introspection. See Custom claims.
customIdTokenClaims (info) => Awaitable<Record<string, any>>
Adds ID token claims. Reserved names are stripped. See ID token claims.
customUserInfoClaims (info) => Awaitable<Record<string, any>>
Adds UserInfo claims. See UserInfo.
authenticationContext { acrValuesSupported, resolve }
Asserts the acr and amr ID token claims for each authorization request or interaction request, such as a device code or a CIBA (Client-Initiated Backchannel Authentication) request, that the user approves on the provider's pages. acrValuesSupported lists the acr values the provider may issue, advertised as acr_values_supported. It must not be empty or contain an empty string, or the plugin fails at startup. resolve returns the acr and amr the current session established. It is not called for requests without the openid scope. Without this option, ID tokens from an approval on the provider's pages carry acr: "0" and no amr. An ID token from completeCibaRequest, or from issueTokens in a grant extension, carries the acr and amr you pass. Without an acr, it carries "0". See Authentication context.
customTokenResponseFields (info) => Awaitable<Record<string, unknown>>
Adds fields to the token response body. Standard fields cannot be overridden. See Custom token response fields.
pairwiseSecret string
Enables pairwise sub values for clients with subject_type: "pairwise". Must be at least 32 characters. See Pairwise subject identifiers.
Clients and registration
grantTypes GrantType[]
Grants the token endpoint accepts. refresh_token requires authorization_code. Extension grants are added on top. Defaults to ["authorization_code", "client_credentials", "refresh_token"].
validateRedirectUri (uri, registeredUris, defaultResult) => Awaitable<boolean>
Replaces exact redirect URI matching. See Custom redirect URI validation.
allowInsecureRedirectUri (url: URL) => boolean
Accepts http redirect and post-logout redirect URIs that the default policy rejects. See HTTP redirect URIs.
cachedTrustedClients Set<string>
Client IDs to cache. Cached clients cannot be changed through the CRUD endpoints. See Trusted clients.
clientPrivileges (context) => Awaitable<boolean | undefined>
Authorizes client actions: create, read, update, delete, list, rotate, and configure-client-credentials-scopes. See Client CRUD privileges.
clientReference (context) => Awaitable<string | undefined>
Returns the owner reference, such as an organization ID, for new clients. See Organizations.
allowDynamicClientRegistration boolean
Enables POST /oauth2/register. Defaults to false. See Dynamic client registration.
allowUnauthenticatedClientRegistration boolean
Accepts registration requests without a session. Defaults to false. Anyone on the internet can then register a client; read Dynamic client registration before you enable it.
validateInitialAccessToken (context) => Awaitable<{ referenceId?, clientCredentialsScopes? } | false>
Enables registration with an initial access token (RFC 7591 §3). referenceId sets the client's owner. clientCredentialsScopes sets the client's scope ceiling for client_credentials and defaults to []. See Dynamic client registration.
clientRegistrationDefaultScopes string[]
Scopes stored on every dynamically registered client. Defaults to scopes, so registered clients get every scope your server defines. Narrow it when you enable open registration.
clientRegistrationAllowedScopes string[]
Extra scopes a registration may ask for. Every value must be in scopes. Defaults to [].
clientRegistrationRequirePKCE boolean
Whether dynamically registered confidential clients require PKCE. Defaults to true. false removes the protection against intercepted and injected codes for every such client, including anonymous ones. See PKCE.
clientRegistrationDefaultApplicationType "web" | "native" | "infer"
application_type used when a registration omits it. Defaults to "web".
clientRegistrationClientSecretExpiration number | string | Date
The client_secret_expires_at value returned to dynamically registered clients that receive a secret. A string such as "30d" is a duration from registration. A number (Unix seconds) or a Date is a fixed time. After that time, the secret is rejected with invalid_client. Defaults to no expiry.
clientRegistrationDefaultResources string[]
Resources linked to every new client, including CIMD, anonymously registered, and admin-created clients. Each must be in resources. Every client that can register can then get tokens for these APIs.
clientRegistrationAllowedResources string[]
Resources a registration may request. Each must be in resources. When both resource options are omitted, requested resources are rejected.
assertionMaxLifetime number
Maximum lifetime in seconds of a private_key_jwt assertion. Defaults to 300. See Private key JWT.
allowClientKeyRotation boolean
Enables POST /oauth2/client/rotate-keys. Startup fails on the memory adapter or with advanced.database.generateId: "serial", which cannot keep assertions single-use. Defaults to false. See Rotating client keys.
Resources
resources Array<string | OAuthResourceInput>
Protected resources seeded into oauthResource at startup. See Resources.
resourceSeedMode "insertOnly" | "merge" | "overwrite"
How seeding treats existing rows: skip them, update only the configured fields, or replace them. Defaults to "insertOnly".
enforcePerClientResources boolean
Requires a client to be linked to every resource it requests (RFC 8707 §2). Defaults to true. false lets any client, including self-registered ones, get tokens for every enabled resource.
cachedResources Set<string>
Resource identifiers to cache. Writes through the admin endpoints invalidate the cache.
identifierValidator (identifier) => Awaitable<boolean>
Validates identifiers created through the admin endpoints or registration. The default requires an absolute URI without a fragment (RFC 8707 §2).
resourcePrivileges (context) => Awaitable<boolean | undefined>
Authorizes resource actions: create, read, update, delete, list, link, and unlink.
Without resourcePrivileges, any signed-in user whose headers reach the admin resource endpoints can manage resources. Define it before calling those endpoints from a route.
Tokens
accessTokenExpiresIn number
Access token lifetime in seconds. Defaults to 3600. See Lifetimes.
m2mAccessTokenExpiresIn number
Lifetime in seconds of client_credentials access tokens. Defaults to 3600.
idTokenExpiresIn number
ID token lifetime in seconds. Defaults to 36000.
refreshTokenExpiresIn number
Refresh token lifetime in seconds. Defaults to 2592000. Each refresh starts a new window, so a regularly used grant does not expire.
codeExpiresIn number
Authorization code lifetime in seconds. Defaults to 600.
scopeExpirations Record<scope, number | string | Date>
Shorter access token lifetimes per scope. The earliest expiry wins.
refreshTokenReuseInterval number
Seconds a rotated refresh token can replay the same response. Defaults to 0. See Refresh tokens.
formatRefreshToken { encrypt, decrypt }
Custom refresh token encoding sent to clients.
disableJwtPlugin boolean
Issues opaque access tokens and HS256 ID tokens. Defaults to false. See Without the JWT plugin.
dpop { proofMaxAgeSeconds?, signingAlgorithms?, nonce? }
DPoP proof validation. proofMaxAgeSeconds defaults to 300, and signingAlgorithms to ["EdDSA", "ES256", "ES512", "PS256", "RS256"]. See DPoP.
nonce takes { required, expiresIn? }. With required: true, DPoP proofs at the token and UserInfo endpoints, and at plugin endpoints that call verifyDpopProof, must carry a nonce the server issued. expiresIn is in seconds and defaults to 300. See Server-provided nonces.
requestUriResolver (input) => Promise<Record<string, string> | null>
Resolves a request_uri at the authorize endpoint for pushed authorization requests (RFC 9126 §4). Return null for an unknown or expired URI.
Storage and generation
storeClientSecret "hashed" | "encrypted" | { hash, verify? } | { encrypt, decrypt }
How client secrets are stored. Hashing requires the JWT plugin; encryption requires disableJwtPlugin. Defaults to "hashed", or "encrypted" with disableJwtPlugin. See Storage.
storeTokens "hashed" | { hash }
How opaque access tokens and refresh tokens are stored. Defaults to "hashed".
prefix { opaqueAccessToken?, refreshToken?, clientSecret? }
Prefixes added to returned values and not stored. Set them before your first deployment; after that, add the prefix in the matching generate* function instead.
generateClientId () => string
Generates client IDs. Defaults to 32 random letters.
generateClientSecret () => string
Generates client secrets. Defaults to 32 random letters.
generateOpaqueAccessToken () => Awaitable<string>
Generates opaque access tokens. Defaults to 32 random letters.
generateRefreshToken () => Awaitable<string>
Generates refresh tokens. Defaults to 32 random letters.
Other
rateLimit object
Per-endpoint rate limits. For the defaults, see Rate limits.
extensions OAuthProviderExtension[]
Companion extensions. Plugins usually call extendOAuthProvider() instead. See Provider extensions.
schema object
Custom model and field names for the plugin tables.
Endpoints
Paths are relative to your auth base path. Each entry lists the HTTP methods, the server method on auth.api, and how the endpoint authenticates. A server-only endpoint is callable through auth.api only. Every other endpoint is also reachable over HTTP.
/.well-known/oauth-authorization-server GET
Server method: getOAuthServerConfig, which is server-only. Auth: none. The auth handler also serves the document over HTTP at its issuer-relative path (RFC 8414 §3). See Expose the well-known metadata.
/.well-known/openid-configuration GET
Server method: getOpenIdConfig, which is server-only. Auth: none. When scopes includes openid, the auth handler also serves the document over HTTP at its issuer-relative path.
/oauth2/authorize GET, POST
Server method: oauth2Authorize. Auth: session, or a redirect to loginPage.
/oauth2/consent POST
Server method: oauth2Consent. Auth: session and signed oauth_query.
/oauth2/continue POST
Server method: oauth2Continue. Auth: session and signed oauth_query.
/oauth2/token POST
Server method: oauth2Token. Auth: client authentication.
/oauth2/introspect POST
Server method: oauth2Introspect. Auth: client authentication.
/oauth2/revoke POST
Server method: oauth2Revoke. Auth: client authentication.
/oauth2/userinfo GET, POST
Server method: oauth2UserInfo. Auth: access token with the openid scope.
/oauth2/end-session GET, POST
Server method: oauth2EndSession. Auth: id_token_hint, or user confirmation.
/oauth2/end-session/confirm POST
No server method. Auth: signed confirmation cookie. HTTP only.
/oauth2/register POST
Server method: registerOAuthClient. Auth: session, initial access token, or none.
/admin/oauth2/create-client POST
Server method: adminCreateOAuthClient. Auth: server call with a session. Server-only.
/admin/oauth2/update-client PATCH
Server method: adminUpdateOAuthClient. Auth: server call with a session. Server-only.
/oauth2/create-client POST
Server method: createOAuthClient. Auth: session.
/oauth2/get-client GET
Server method: getOAuthClient. Auth: session.
/oauth2/public-client GET
Server method: getOAuthClientPublic. Auth: session.
/oauth2/public-client-prelogin POST
Server method: getOAuthClientPublicPrelogin. Auth: signed oauth_query. The endpoint requires allowPublicClientPrelogin.
/oauth2/get-clients GET
Server method: getOAuthClients. Auth: session.
/oauth2/update-client POST
Server method: updateOAuthClient. Auth: session.
/oauth2/client/rotate-secret POST
Server method: rotateClientSecret. Auth: session.
/oauth2/client/rotate-keys POST
Server method: rotateClientKeys. Auth: client assertion.
/oauth2/delete-client POST
Server method: deleteOAuthClient. Auth: session.
/oauth2/get-consent GET
Server method: getOAuthConsent. Auth: session.
/oauth2/get-consents GET
Server method: getOAuthConsents. Auth: session.
/oauth2/update-consent POST
Server method: updateOAuthConsent. Auth: session.
/oauth2/delete-consent POST
Server method: deleteOAuthConsent. Auth: session.
/admin/oauth2/resources POST
Server method: adminCreateOAuthResource. Auth: session and resourcePrivileges. Server-only.
/admin/oauth2/resources GET
Server method: adminListOAuthResources. Auth: session and resourcePrivileges. Server-only.
/admin/oauth2/resources/:identifier GET
Server method: adminGetOAuthResource. Auth: session and resourcePrivileges. Server-only.
/admin/oauth2/resources/:identifier PATCH
Server method: adminUpdateOAuthResource. Auth: session and resourcePrivileges. Server-only.
/admin/oauth2/resources/:identifier DELETE
Server method: adminDeleteOAuthResource. Auth: session and resourcePrivileges. Server-only.
/admin/oauth2/resources/:identifier/clients/:client_id POST
Server method: adminLinkClientResource. Auth: session and resourcePrivileges. Server-only.
/admin/oauth2/resources/:identifier/clients/:client_id DELETE
Server method: adminUnlinkClientResource. Auth: session and resourcePrivileges. Server-only.
In the browser, oauthProviderClient() adds the signed oauth_query from the page URL to POST requests. /oauth2/register rejects requests unless allowDynamicClientRegistration is on, and /oauth2/client/rotate-keys unless allowClientKeyRotation is on.
Some endpoints behave differently with other plugins or requests:
- With
oauthDeviceAuthorization(),/oauth2/authorizealso acceptsuser_codeinstead of an authorization request. The user approves the device code on the same pages. See Device code grant. - With
ciba(),/oauth2/authorizealso acceptsciba_request_id. The user approves the backchannel request on the same pages. See What the user sees. - During a browser navigation,
/oauth2/end-sessioncan return the front-channel logout page. /oauth2/token,/oauth2/introspect, and/oauth2/revokereturn 400invalid_requestfor a parameter sent more than once. At the token endpoint, onlyresourceandaudiencemay repeat.
Token errors
Errors use the RFC 6749 §5.2 format. The built-in grants authenticate the client before they look up the grant, so an unknown client_id returns invalid_client, not invalid_grant.
invalid_request 400
Returned when a required request field is missing or malformed, or a parameter is sent more than once. Only resource and audience may repeat.
invalid_client 400
Returned in any of these cases:
- Client authentication fails.
- The client uses a method other than its registered
token_endpoint_auth_method.
invalid_client 401
Returned when client_secret_basic authentication fails. The response carries a WWW-Authenticate: Basic challenge.
invalid_grant 400
Returned when the code, refresh token, or PKCE verifier is invalid, expired, or issued to another client.
invalid_user 400
Returned when the user who approved an authorization code was deleted before the code was exchanged.
unauthorized_client 400
Returned in any of these cases:
- The client is not registered for the grant.
- A public client uses
client_credentials. - The client has no
client_credentialsscopes.
unsupported_grant_type 400
Returned when the grant is not in grantTypes and no extension handles it.
invalid_scope 400
Returned in any of these cases:
- A requested scope is not allowed for the client.
- No scope is allowed for a requested resource.
invalid_target 400
Returned in any of these cases:
- A
resourceis malformed, unknown, or disabled. - A
resourceis not linked to the client whileenforcePerClientResourcesis on.
invalid_dpop_proof 400
Returned when the DPoP proof is missing or invalid for a DPoP-bound client or resource.
use_dpop_nonce 400
Returned when dpop.nonce.required is on and the DPoP proof has no nonce, or one that expired or that this server did not issue. The DPoP-Nonce response header carries the nonce to retry with. The UserInfo endpoint returns the same error with a 401 and a WWW-Authenticate: DPoP challenge.
Token exchange has its own conditions for these errors. See Token exchange errors.
When adminCreateOAuthClient links resources, an invalid identifier fails validation with VALIDATION_ERROR, an unknown or disabled resource returns invalid_target, and a resourcePrivileges denial returns 401. The call creates nothing in each case.
Rate limits
Limits apply per IP and per endpoint, and only when Better Auth rate limiting is enabled, which by default is production only.
| Option key | Endpoint | Window | Max |
|---|---|---|---|
token | /oauth2/token | 60s | 20 |
authorize | /oauth2/authorize | 60s | 30 |
introspect | /oauth2/introspect | 60s | 100 |
revoke | /oauth2/revoke | 60s | 30 |
register | /oauth2/register | 60s | 5 |
rotateClientKeys | /oauth2/client/rotate-keys | 60s | 5 |
userinfo | /oauth2/userinfo | 60s | 60 |
Override a limit with { window, max }, or set it to false to fall back to the global limits:
oauthProvider({
rateLimit: {
token: { window: 60, max: 50 },
introspect: false,
},
})Provider extensions
Companion plugins call extendOAuthProvider() from their init() hook to add token grants, assertion-based client authentication, discovery metadata, claims, client registration metadata, client-id discovery, and interaction requests. The CIMD plugin uses this to add URL-based client discovery.
An interaction request is a request other than an authorization request that the user approves through the /oauth2/authorize sign-in, account selection, post-login, and consent pages. It is approved when the user accepts consent, instead of issuing an authorization code. oauthDeviceAuthorization() uses one keyed by user_code, and ciba() one keyed by ciba_request_id.
Add companion plugins such as oauthDeviceAuthorization() and oauthTokenExchange() to every betterAuth() instance that registers OAuth clients, including a separate admin or provisioning instance. An instance without the plugin does not support its extension grant:
createOAuthClient,adminCreateOAuthClient, and client updates reject the grant withinvalid_client_metadata.- Dynamic registration drops the grant and registers the client with its other supported grants. It fails with
invalid_client_metadataonly when no supported grant remains. - A client metadata document keeps the grant, and the token endpoint refuses it with
unsupported_grant_type. The document fails withinvalid_client_metadataonly when it lists no supported grant.
import type { BetterAuthPlugin } from "better-auth";
import { extendOAuthProvider } from "@better-auth/oauth-provider";
export const customOAuthExtension = () =>
({
id: "custom-oauth-extension",
init(ctx) {
extendOAuthProvider(ctx, {
grants: {
"urn:example:params:oauth:grant-type:custom": async ({ provider }) => {
const scopes = ["openid"];
// Passing the scopes checks them against the client's registered
// scopes. Without them, the call only authenticates the client.
const { client } = await provider.authenticateClient({ scopes });
return provider.issueTokens({ client, scopes });
},
},
metadata: () => ({ custom_grant_supported: true }),
});
},
}) satisfies BetterAuthPlugin;grants,clientAuthentication, andinteractionRequestsmust not overlap across extensions. A duplicate grant type, auth method, assertion type, or interaction parameter fails at startup. Extension grants and auth methods are advertised in discovery.metadataandclaimsonly add keys. A key the provider owns is kept, and a key two extensions contribute resolves to the first one registered. To advertise extension claims, setadvertisedMetadata.claims_supported.- A
clientDiscoveryentry has a stableidstored as client provenance. Changing it requires migrating the owned clients, and removing it makes them fail closed.
A grant handler receives provider (getClient, authenticateClient, resolveConfirmation, issueTokens, verifyDpopProof, issueDpopNonce, hashToken, validateAccessToken, requireActiveAccessToken). Other endpoints get the same object from getOAuthProviderApi(ctx, opts, grantType?). Without grantType, issueTokens throws. validateAccessToken can return an inactive payload; protected endpoints should use requireActiveAccessToken, which rejects inactive tokens with a bearer challenge.
issueTokens applies the provider's resource policy. Each resource must be registered and enabled, and linked to the client while enforcePerClientResources is on (the default). Each resource's allowedScopes also applies. It does not re-check anything else it is given. Validate the user, the client's registered scopes, and any grant-specific policy in your handler before calling it. Pass scopes to authenticateClient so a client cannot obtain scopes it was never registered for.
When a companion endpoint accepts application/x-www-form-urlencoded, set cloneRequest: true in its endpoint options before calling authenticateClient(). Client authentication re-reads the raw form body to check that client credentials are not repeated or combined across authentication methods. The endpoint must therefore keep a readable request after parsing the form.
To bind a token with cnf (RFC 7800 §3), pass confirmation to issueTokens. A clientAuthentication strategy can also return the sender constraint it proved as confirmation, such as a DPoP key thumbprint (jkt) or a certificate thumbprint (x5t#S256):
- The built-in
client_credentialsgrant binds its token to that confirmation. - An extension grant receives it from
authenticateClient()and passes it toissueTokens. - The built-in
authorization_codeandrefresh_tokengrants do not use it.
With a jkt confirmation, the token response has token_type: DPoP. The client must then send a DPoP proof signed by that key when it calls a protected resource.
A confirmation that is not a DPoP key cannot replace a required DPoP binding. When the client is registered with dpop_bound_access_tokens: true, or a resource sets dpopBoundAccessTokensRequired: true, issuance with such a confirmation fails with invalid_dpop_proof. provider.resolveConfirmation() fails the same way, so a grant that calls it before consuming a one-time credential keeps that credential for a retry.
A confirmation has exactly one member, and its value is a non-empty string: jkt for a DPoP key, or x5t#S256 for an mTLS certificate. A confirmation with any other shape fails the request with server_error. This applies whether a clientAuthentication strategy returns it or you pass it to issueTokens or resolveConfirmation. No token is issued.
Claim contributors cannot set cnf.
A clientAuthentication strategy must return the same confirmation whenever the client proves the same key. Token exchange compares it with the cnf of the client's own subject token.
A grant that consumes a one-time credential, such as a device code, should resolve the binding before it claims the credential. provider.resolveConfirmation({ client, scopes, resources, confirmation }) returns the confirmation the client proved at authentication. Without one, it verifies the request's DPoP proof by the same rules issueTokens applies. Pass the result to issueTokens as confirmation. A rejected proof then fails before the credential is consumed, so the client can retry with a valid one.
To stop a stolen DPoP-bound token from being reissued under another key, a grant that reissues an existing token can require that token's key. Verify the existing token first. When the caller is the client the token was issued to, pass the token's key thumbprint as expectedJkt, as the built-in refresh and token exchange grants do. Another party, such as a resource server, cannot hold that key.
import { getConfirmationJkt } from "better-auth/oauth2";
const confirmation = await provider.resolveConfirmation({
client,
scopes,
resources,
confirmation: authenticated.confirmation,
expectedJkt: getConfirmationJkt(verifiedToken.cnf),
});The request must then carry a DPoP proof signed by that key, or client authentication must return a confirmation with the same jkt. A returned confirmation replaces the proof, so one with another key fails even when the proof uses the expected key. Anything else fails with invalid_dpop_proof, including an mTLS confirmation. With dpop.nonce.required, a proof without a current nonce gets use_dpop_nonce instead, so the client can retry. If the existing token is not DPoP-bound, getConfirmationJkt returns undefined and the usual rules apply.
Client registration metadata
An extension that defines its own client registration fields, such as CIBA's backchannel_token_delivery_mode, declares them in clientMetadata. The provider stores the fields in the client's metadata. validate runs whenever a client is registered through /oauth2/register or a client metadata document, or an admin creates or updates it. A bad value is therefore rejected with invalid_client_metadata at registration, not when the client first uses it.
extendOAuthProvider(ctx, {
clientMetadata: {
fields: ["example_mode"],
validate: ({ metadata }) => {
if (metadata.example_mode !== undefined && metadata.example_mode !== "ok") {
throw new APIError("BAD_REQUEST", {
error: "invalid_client_metadata",
error_description: "example_mode must be ok",
});
}
},
},
});Dynamic registration ignores top-level fields it does not recognize (RFC 7591 §2). Fields an extension declares are the exception:
- A registrant sends them as top-level fields, and the provider stores them in
metadata. A registrant cannot set any othermetadatakey. - An admin sets the same fields inside
metadata. - A client metadata document carries them as top-level members of the document. The document owns those fields: each refresh replaces them in
metadata, removing any it no longer declares, and keeps othermetadatakeys, such as ones an admin set.
An extension cannot declare a core client field such as redirect_uris, or a server-owned field such as disabled, reference_id, or client_credentials_scopes. The provider rejects these at setup. validate receives the core registration metadata after defaults as client, and the client's metadata. Read extension fields from metadata.
Client authentication obligations
A clientAuthentication strategy proves which client sent the assertion and returns its clientId. The provider loads and authorizes the client record itself. After verifying the signature, the strategy must bind the audience, bound the lifetime, and reject replayed jti values (RFC 7523 §3). consumeClientAssertion performs all three:
import { consumeClientAssertion } from "@better-auth/oauth-provider";
import { APIError } from "better-auth/api";
authenticate: async ({ ctx, opts, assertion, expectedAudience }) => {
if (!expectedAudience) throw new APIError("BAD_REQUEST", { error: "invalid_client" });
const payload = await verifyAssertionSignature(assertion); // your key source
await consumeClientAssertion(ctx, opts, {
namespace: `urn:example:attestation:${payload.sub}`,
payload,
expectedAudience,
});
return { clientId: payload.sub };
};Claim precedence
Extension claims only add claim names. Your own callbacks can override profile claims. The provider always owns identity, lifetime, binding, and authentication-context claims.
| Token | Order, lowest to highest authority | Owned by the provider |
|---|---|---|
| Access token | extension claims.accessToken < per-issuance accessTokenClaims < customAccessTokenClaims < per-resource customClaims | iss, sub, aud, exp, iat, jti, client_id, scope, auth_time, acr, amr, cnf, reference_id, stripped before signing. The provider also sets azp and sid after contributed claims. |
| ID token | subject and authentication claims < customIdTokenClaims. Extension and per-issuance idTokenClaims only add names and cannot set profile or email claims. | iss, sub, aud, exp, nbf, iat, jti, nonce, sid, at_hash, c_hash, s_hash, auth_time, acr, amr, azp |
| UserInfo | scope and claims.userinfo claims < extension claims.userInfo (add only) < customUserInfoClaims | sub, applied last |
Per-issuance accessTokenClaims are signed into JWT access tokens, so introspecting a JWT access token returns them. An opaque access token stores no per-issuance claims, so introspecting it does not return them. A claim that introspection of an opaque token must return belongs in a claims.accessToken contributor that does not depend on the grant type.
Schema
The plugin adds the following tables. Run npx auth generate for the exact schema of your adapter.
OAuth Client
Table Name: oauthClient
OAuth Resource
Table Name: oauthResource
A null policy field uses the plugin default at issuance.
OAuth Client Resource
Table Name: oauthClientResource
Links a client to a resource. The pair (clientId, resourceId) is unique. enforcePerClientResources controls whether authorization and token requests check these rows. Introspection always uses them to decide whether a resource server can introspect another client's token.
OAuth Refresh Token
Table Name: oauthRefreshToken
OAuth Access Token
Table Name: oauthAccessToken
Stores opaque access tokens only. JWT access tokens are not stored.
OAuth Consent
Table Name: oauthConsent
OAuth Client Assertion
Table Name: oauthClientAssertion
Records each private_key_jwt assertion jti so it can be used once. The check needs string IDs, so with advanced.database.generateId: "serial" Better Auth logs a warning. Rows are never pruned; delete expired rows.
Optimizations
Database adapters may map clientId on oauthClient to id for faster lookups. The id column must then accept strings shaped like UUIDs and URLs.
Related
OAuth Provider setup
Install the plugin and run your first authorization code flow.
Clients and registration
Register, manage, and authenticate OAuth clients.
Tokens, scopes, and resources
Control which tokens the provider issues and for how long.
Client ID Metadata Documents
Identify clients by a metadata document URL.
Client-Initiated Backchannel Authentication
Let a client ask a known user to approve access on their own device.