OpenID Connect and logout
Configure discovery, ID token and UserInfo claims, subject identifiers, and logout.
Your OAuth provider is also an OpenID Connect provider. A client that requests the openid scope receives an ID token, can call UserInfo, and can take part in logout.
To serve only OpenID Connect, set requireOpenId. A request to /oauth2/authorize that leaves out openid, or sends no scope, is then redirected to the client with invalid_scope instead of being served as plain OAuth. The redirect happens once the client and redirect_uri have passed validation. Earlier failures use the server's error page. The option does not apply to device authorization requests. openid must also be in scopes, or the plugin fails at startup:
oauthProvider({
scopes: ["openid", "profile", "email"],
requireOpenId: true,
// ...
});Discovery metadata
Better Auth serves OpenID Provider metadata at {issuer}/.well-known/openid-configuration and authorization server metadata at {issuer}/.well-known/oauth-authorization-server. If your framework does not forward these routes to auth.handler, see Expose the well-known metadata.
The OpenID configuration returns 404 when you set scopes without openid. To serve it, add openid to scopes.
The issuer keeps the scheme of your baseURL, or of jwt.issuer when you set it, so discovery, the authorization response iss parameter, and issued tokens report the same value. If a proxy terminates TLS in front of Better Auth, set baseURL to the public https URL.
To publish fewer scopes, more claims, or a different list of token endpoint authentication methods than discovery derives, set advertisedMetadata:
oauthProvider({
scopes: ["openid", "profile", "email", "offline_access", "read:post"],
advertisedMetadata: {
scopes_supported: ["openid", "profile", "read:post"],
claims_supported: [
"sub", "iss", "aud", "exp", "iat", "sid", "scope", "azp",
"name", "picture", "given_name", "family_name",
"locale", "https://example.com/org",
],
token_endpoint_auth_methods_supported: [
"none", "client_secret_basic", "client_secret_post", "private_key_jwt",
],
},
})Every value in scopes_supported must also be in scopes, or the plugin fails at startup. claims_supported replaces the default list (sub, iss, aud, exp, iat, sid, scope, azp, plus the profile and email claims when those scopes are configured), so repeat the defaults you still want. List every claim your custom claim functions add, so clients know to expect it. Clients can request through claims.userinfo only the names in this list.
token_endpoint_auth_methods_supported replaces the derived list in both discovery documents, so list every method you want clients to see. Unset, none appears only when allowUnauthenticatedClientRegistration is true or an extension contributes client discovery. A provider that keeps registration protected but accepts public clients you create yourself would otherwise omit none, and clients that follow RFC 8414 would conclude that public clients are unsupported. Include none to say otherwise. Every listed method must be one the server supports, including methods that a companion plugin adds through extendOAuthProvider. The list cannot be empty or repeat a method, or the plugin fails at startup. An unsupported method throws when discovery metadata is built. The option changes only what discovery advertises: it does not change which clients the token endpoint accepts, it does not open /oauth2/register, and it leaves the introspection and revocation lists unchanged.
ID token claims
To add claims to the ID token, set customIdTokenClaims. It receives the user, the granted scopes, and the client's metadata. It returns an object of claims to add:
oauthProvider({
customIdTokenClaims: ({ user, scopes, metadata }) => ({
"https://example.com/org": user.organizationId,
}),
})- In the authorization code flow,
profileandemailclaims go to UserInfo, not the ID token. Add them incustomIdTokenClaimsif a client needs them in the ID token. - Better Auth owns the protocol claims (
iss,sub,aud,exp,nbf,iat,jti,nonce,sid,at_hash,c_hash,s_hash,auth_time,acr,amr,azp). Custom values for these names are dropped with a warning log. - Use URI-namespaced names for application claims, as OIDC Core §5.1.2 recommends.
- To stop issuance, for example when the user has left the organization, throw from the function.
When an extension also contributes claims, see Claim precedence.
Better Auth advertises acr_values_supported: ["0"] and always issues acr: "0", meaning the authentication did not meet ISO/IEC 29115 level 1 (OIDC Core §2). Custom ACR policies are not supported. A request for other acr_values still succeeds, but an essential claims.id_token.acr request that does not allow "0" fails. The authorization request ends with an access_denied error on the redirect to the client. The Unmet Authentication Requirements specification says the provider SHALL return unmet_authentication_requirements in this case. Better Auth returns access_denied.
With disableJwtPlugin: true, ID tokens are signed with HS256 using the client secret, so public clients get no ID token. See Without the JWT plugin. The OpenID configuration then omits jwks_uri, because there are no keys to publish, and lists ["HS256"] in id_token_signing_alg_values_supported. OIDC Discovery §3 marks jwks_uri as required.
UserInfo
/oauth2/userinfo accepts GET and POST and returns claims for an access token whose scopes include openid. A token without openid gets 400 invalid_scope. An expired or revoked token, or one whose session has ended, gets 401 invalid_token (RFC 6750 §3.1).
Every 401 from UserInfo carries a WWW-Authenticate challenge that tells the client how to retry. The response also lists WWW-Authenticate in Access-Control-Expose-Headers, so a browser client on another origin can read the challenge.
| Request | Challenge |
|---|---|
| No access token | Bearer, DPoP algs="…", with no error code |
A token sent with the Bearer scheme or in the form body, when the token is not DPoP-bound | Bearer error="invalid_token", … |
A DPoP-bound token, or any request that uses the DPoP scheme | DPoP error="…", error_description="…", algs="…" (RFC 9449 §7.1) |
algs lists the proof algorithms from dpop.signingAlgorithms. UserInfo validates the access token before it checks the DPoP proof, so an invalid, expired, or revoked token gets invalid_token whatever the proof contains. For a valid DPoP-bound token, the error is invalid_dpop_proof when the proof is missing or fails verification, for example when its htu, htm, or key does not match. Every other failure gets invalid_token, including a DPoP-bound token sent with the Bearer scheme. An auth.api.oauth2UserInfo call has no HTTP request to check a proof against, so a DPoP-bound token fails with invalid_token, and the thrown error carries the same challenge in its headers.
const response = await fetch("https://auth.example.com/api/auth/oauth2/userinfo", {
headers: { Authorization: `Bearer ${accessToken}` },
});Claims follow the granted scopes:
| Scope | Claims |
|---|---|
openid | sub |
profile | name, picture, given_name, family_name |
email | email, email_verified |
When a claim from the table above is requested through the claims.userinfo parameter and appears in claims_supported, Better Auth returns it if a value exists, even when its scope was not granted. Better Auth does not fill in other requested names, such as locale. To return them, read requestedClaims in customUserInfoClaims, described below. A value that is null or unset is omitted, not returned as null. An empty string is returned as is, as the next paragraph explains. This per-claim selection works only with opaque access tokens. With a JWT access token, UserInfo returns only the claims its scopes cover.
Better Auth does not treat an empty string as a missing value, so a user whose name is "" gets name: "". OIDC Core §5.3.2 says a claim that is not returned should be omitted, and should not be present with a null or empty string value.
Better Auth reads only the claim names under claims.userinfo. It ignores essential, value, and values there, and it ignores claims.id_token requests except acr. OIDC Core §5.5.1 says a claim whose value does not match a requested value is left out of the response. It also says a mismatch on sub must cause the authentication to fail, and §3.1.2.2 says the provider must not reply with a token for a different user. Better Auth ignores a value on sub too. A client that requests a specific sub must check the sub it receives.
To add claims to the UserInfo response, set customUserInfoClaims. It receives the user, the access token's scopes, the access token payload as jwt, and requestedClaims. requestedClaims lists the claim names requested through claims.userinfo. It returns an object of claims to add:
oauthProvider({
customUserInfoClaims: ({ user, scopes, requestedClaims, jwt }) => ({
locale: "en-GB",
...(requestedClaims.includes("website") ? { website: user.website } : {}),
}),
})A returned claim replaces the standard claim of the same name, except sub.
Pairwise subject identifiers
Clients that receive the same sub for a user can link that user's activity across those clients. By default, sub is the user ID, which is the same for every client (the public subject type). To let clients receive a sub that other clients cannot correlate, set pairwiseSecret:
oauthProvider({
pairwiseSecret: process.env.PAIRWISE_SECRET, // at least 32 characters
})Discovery then lists "public" and "pairwise" in subject_types_supported. A client opts in with subject_type: "pairwise" through dynamic registration or adminCreateOAuthClient. createOAuthClient ignores the field.
Better Auth computes the value with HMAC-SHA256 over the host of the client's first redirect URI and the user ID (OIDC Core §8.1). Clients that share a redirect host share the same sub.
The calculation assumes that user IDs contain no dot. OIDC Core §8.1 says different sector identifiers must produce different subject values, and a dot in a user ID can break that. The built-in ID generators (the default, uuid, and serial) never produce a dot. If a custom advanced.database.generateId function or your database assigns user IDs, make sure they contain no dot when you use pairwise subjects.
- Pairwise
subappears in the ID token, UserInfo, and introspection. Introspection returns thesubof the client the token was issued to. - JWT access tokens keep the real user ID as
sub, so resource servers can look users up. A client can decode its own JWT access tokens, so a pairwise client that requests aresourcelearns the real user ID. To keep the user ID from a pairwise client, have it request opaque tokens by omittingresource.
pairwiseSecret must be at least 32 characters. Changing it changes every pairwise sub and breaks existing client accounts. Treat it as permanent.
sector_identifier_uri is not supported. All redirect_uris of a pairwise client must therefore share one host and port. Pairwise clients also cannot use custom-scheme redirect URIs with a host, such as app://rp.example.com/callback. Any app can claim a custom scheme, and that app would receive the same sub as a pairwise web client that redirects to rp.example.com. Registration fails with invalid_client_metadata in either case. OIDC Core §8.1 and OIDC Registration §2 say a provider that uses pairwise subjects should use sector_identifier_uri. Better Auth does not read it. It rejects a registration that would need it instead of deriving a sub from the wrong sector.
RP-initiated logout
To let a client end the user's session, register it with enable_end_session: true. The /oauth2/end-session endpoint then implements RP-Initiated Logout for it:
await auth.api.adminCreateOAuthClient({
headers,
body: {
redirect_uris: ["https://app.example.com/callback"],
post_logout_redirect_uris: ["https://app.example.com/logout"],
enable_end_session: true,
},
});-
It accepts GET query parameters, a form-encoded POST body, or a JSON POST body.
authClient.oauth2.endSession()sends a JSON body when you pass the fields directly. -
A valid
id_token_hintfor the current browser session ends it immediately. Without one, or with a hint for a different session, the user must confirm first. In a browser, Better Auth serves the confirmation page. -
Better Auth redirects after logout only when
post_logout_redirect_uriexactly matches one of the client's registeredpost_logout_redirect_uris, and addsstateonly to that redirect. For example,https://app.example.com/logout/does not match a registeredhttps://app.example.com/logout. Without a matching URI, a browser shows a logged-out page from Better Auth. -
An
id_token_hintthat fails validation gets one of these answers:- On a browser navigation with a current session, the user sees the confirmation page, as when no hint is sent. If the request carries a
client_idand a registeredpost_logout_redirect_uri, the redirect happens after the user confirms. - In any other case, the endpoint returns 401
invalid_token, as JSON or, for a browser navigation, as an error page. It does not redirect. - When no client is found, the second answer is 400
invalid_client, and the confirmation in the first answer ends without a redirect.
A disabled client gets 400
invalid_client, and a client withoutenable_end_sessiongets 401invalid_client, before the hint is checked.RP-Initiated Logout §4 says the provider must not redirect to the client when it detects an error in the request. Better Auth redirects after the user confirms.
- On a browser navigation with a current session, the user sees the confirmation page, as when no hint is sent. If the request carries a
Enable this only for clients you trust. The client, or anyone holding an ID token it received, can end that token's session without confirmation, for these reasons:
- With a valid
id_token_hint, the request does not need the user's browser. - An expired ID token is still accepted as a hint.
Ending the session also triggers back-channel logout for every client that holds tokens for it.
Back-channel logout
To notify a client when a user's session ends, register a backchannel_logout_uri for it. The session can end in several ways, for example through sign-out, end-session, or admin revocation. Better Auth then sends a signed Logout Token to each client that registered a URI and holds tokens for that session:
await auth.api.adminCreateOAuthClient({
headers,
body: {
redirect_uris: ["https://app.example.com/callback"],
backchannel_logout_uri: "https://app.example.com/logout/backchannel",
backchannel_logout_session_required: true,
},
});- Recipients are found through the opaque access tokens and refresh tokens stored for the session. A client that holds only a JWT access token for it, such as after a
resourcerequest withoutoffline_access, is not notified. - Logout Tokens carry
typ: logout+jwt, always includesid, and live for 120 seconds. The JWT plugin signs them, so a client verifies them with your JWKS. Each request has a 5 second timeout and is not retried. - Better Auth also revokes the session's access tokens and its refresh tokens without
offline_access. Introspection and UserInfo then reject those access tokens, but a resource server that verifies JWT access tokens locally keeps accepting them until they expire. An opaque access token issued by a refresh that runs while sign-out is in progress can also stay active until it expires, on databases that enforce the session foreign key. Refresh tokens withoffline_accesssurvive, as §2.7 allows. Tokens from the device authorization grant are not tied to a session, so sign-out does not end them. - A new grant gets a refresh token only when it includes
offline_access, and that token survives the end of the session. RFC 10017 §6.3.2.3 says authorization servers should link the lifetime of a refresh token to the user's authenticated session when the client is a browser-based app. The provider has no option that binds every refresh token to the session. A browser-based app whose tokens must end with the session has two choices. It can omitoffline_access, which means it gets no refresh token and must authorize again when its access token expires. Or it can keep its tokens on a server that handles back-channel logout. backchannel_logout_urimust be a publichttpsURL with no credentials or fragment. Loopback, private, and metadata hosts are rejected withinvalid_client_metadata. The check does not resolve DNS, so a public name that resolves to a private address passes. If untrusted parties can register clients on your server, block outbound requests from the auth server to private networks.- Clients registered through CIMD cannot use back-channel logout.
Back-channel logout requires the JWT plugin, which signs Logout Tokens. With disableJwtPlugin: true, registering a backchannel_logout_uri fails and discovery advertises backchannel_logout_supported: false.
Delivery runs through advanced.backgroundTasks.handler when one is set, so a slow client cannot delay sign-out. Without a handler it runs before the sign-out response returns, so set one if you deploy to serverless runtimes.