> You are reading Better Auth documentation for `v1.8 (Beta)`. This is not the current stable release. APIs may differ from the latest stable version.

# OpenID Connect and logout (/docs/beta/plugins/oauth-provider/openid-connect)

Configure discovery, ID token and UserInfo claims, authentication context, subject identifiers, and logout.



Your OAuth provider is also an [OpenID Connect](https://openid.net/specs/openid-connect-core-1_0.html) provider. A client that requests the `openid` scope receives an ID token, can call UserInfo, and can take part in logout.

## Discovery metadata [#discovery-metadata]

Better Auth serves [OpenID Provider metadata](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig) at `{issuer}/.well-known/openid-configuration` and [authorization server metadata](https://datatracker.ietf.org/doc/html/rfc8414#section-3) at `{issuer}/.well-known/oauth-authorization-server`. If your framework does not forward these routes to `auth.handler`, see [Expose the well-known metadata](/docs/beta/plugins/oauth-provider#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, or more claims, than the server supports, set `advertisedMetadata`:

```ts title="auth.ts"
oauthProvider({
  scopes: ["openid", "profile", "email", "offline_access", "read:post"],
  advertisedMetadata: { // [!code highlight]
    scopes_supported: ["openid", "profile", "read:post"], // [!code highlight]
    claims_supported: [ // [!code highlight]
      "sub", "iss", "aud", "exp", "iat", "sid", "scope", "azp", // [!code highlight]
      "name", "picture", "given_name", "family_name", // [!code highlight]
      "locale", "https://example.com/org", // [!code highlight]
    ], // [!code highlight]
  }, // [!code highlight]
})
```

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.

Better Auth advertises `acr_values_supported` from `authenticationContext.acrValuesSupported`, which defaults to `["0"]`. In OIDC Core, `"0"` means the authentication did not meet ISO/IEC 29115 level 1. To assert other classes, see [Authentication context](#authentication-context).

## ID token claims [#id-token-claims]

To add claims to the [ID token](https://openid.net/specs/openid-connect-core-1_0.html#IDToken), set `customIdTokenClaims`. It receives the `user`, the granted `scopes`, and the client's `metadata`. It returns an object of claims to add:

```ts title="auth.ts"
oauthProvider({
  customIdTokenClaims: ({ user, scopes, metadata }) => ({ // [!code highlight]
    "https://example.com/org": user.organizationId, // [!code highlight]
  }), // [!code highlight]
})
```

* In the authorization code flow, `profile` and `email` claims go to UserInfo, not the ID token. Add them in `customIdTokenClaims` if 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](https://openid.net/specs/openid-connect-core-1_0.html#AdditionalClaims) 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](/docs/beta/plugins/oauth-provider/reference#claim-precedence).

By default, ID tokens carry `acr: "0"`, meaning the authentication did not meet ISO/IEC 29115 level 1 ([OIDC Core §2](https://openid.net/specs/openid-connect-core-1_0.html#IDToken)), and no `amr`. To assert other values, see [Authentication context](#authentication-context).

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](/docs/beta/plugins/oauth-provider/tokens#without-the-jwt-plugin).

## Authentication context [#authentication-context]

To assert a stronger authentication class in `acr`, or the methods the user signed in with in `amr`, set `authenticationContext` with both fields:

* `acrValuesSupported` lists the `acr` values the provider may issue. Discovery advertises it as `acr_values_supported`. Include `"0"` if `resolve` can return no `acr`.
* `resolve` returns the `acr` and `amr` the current session established. For requests with the `openid` scope, it runs once, when the user approves an authorization request, a device code, or a [CIBA (Client-Initiated Backchannel Authentication)](/docs/beta/plugins/ciba) request on the provider's pages. It receives `user`, `session`, `client`, the approved `scopes`, the request `headers`, and `requestedAcrValues` (from `claims.id_token.acr` and `acr_values`). [`completeCibaRequest`](/docs/beta/plugins/ciba#decide-from-your-own-app) does not call `resolve`, and records the `acr` and `amr` you pass instead.

Return only what the session proved. Better Auth does not record how a session signed in, so track it yourself. The example below marks sessions created by a completed two-factor challenge. Sessions created through a trusted device skip that challenge and stay unmarked.

```ts title="auth.ts"
import { betterAuth } from "better-auth";
import { jwt, twoFactor } from "better-auth/plugins";
import { oauthProvider } from "@better-auth/oauth-provider";

const MFA = "urn:example:acr:mfa";

export const auth = betterAuth({
  session: {
    additionalFields: {
      twoFactorVerified: { type: "boolean", defaultValue: false, input: false },
    },
  },
  databaseHooks: {
    session: {
      create: {
        // Two-factor verification endpoints create the session only after the
        // second factor succeeds.
        before: async (session, ctx) => ({
          data: {
            ...session,
            twoFactorVerified:
              ctx?.path?.startsWith("/two-factor/verify-") ?? false,
          },
        }),
      },
    },
  },
  disabledPaths: ["/token"],
  plugins: [
    twoFactor(),
    jwt({ disableSettingJwtHeader: true }),
    oauthProvider({
      loginPage: "/sign-in",
      consentPage: "/consent",
      authenticationContext: { // [!code highlight]
        acrValuesSupported: ["0", MFA], // [!code highlight]
        // Assert only what the session proved: the two-factor step, not how the
        // first factor was done.
        resolve: ({ session }) => // [!code highlight]
          session.twoFactorVerified === true // [!code highlight]
            ? { acr: MFA, amr: ["mfa"] } // [!code highlight]
            : { acr: "0" }, // [!code highlight]
      }, // [!code highlight]
    }),
  ],
});
```

How a request for a class is handled depends on whether it is essential:

* An essential request (`claims={"id_token":{"acr":{"essential":true,"value":"…"}}}`) that the session does not satisfy fails with `access_denied` at the client's redirect URI. If no value in `acrValuesSupported` could satisfy it, the request fails before sign-in.
* A voluntary request (`acr_values`, or an `acr` claim without `essential`) never fails. The ID token reports the session's current `acr`.

`resolve` must return an `acr` from `acrValuesSupported`, or omit it to use `"0"`. `amr` must be an array of strings. Any other result fails the authorization with `server_error`.

To refuse an authorization yourself, throw an `APIError` with an OAuth `error` such as `access_denied`. The client receives that error and its `error_description`. For a device code, the user sees the error on your verification page instead, and the code stays pending so the user can retry.

The `acr` and `amr` are stored with the authorization code or device code and with the refresh token. ID tokens from later refreshes therefore keep the values of the original authentication ([OIDC Core §12.2](https://openid.net/specs/openid-connect-core-1_0.html#RefreshTokenResponse)). They change only when the user authorizes again.

## UserInfo [#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](https://datatracker.ietf.org/doc/html/rfc6750#section-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](https://datatracker.ietf.org/doc/html/rfc9449#section-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. When [`dpop.nonce.required`](/docs/beta/plugins/oauth-provider/tokens#server-provided-nonces) is on, a proof without a current server nonce gets `use_dpop_nonce` instead, and the response carries a `DPoP-Nonce` header to retry with. 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`.

```ts
const response = await fetch("https://auth.example.com/api/auth/oauth2/userinfo", {
  headers: { Authorization: `Bearer ${accessToken}` },
});
```

Claims follow the granted [scopes](https://openid.net/specs/openid-connect-core-1_0.html#ScopeClaims):

| Scope     | Claims                                         |
| --------- | ---------------------------------------------- |
| `openid`  | `sub`                                          |
| `profile` | `name`, `picture`, `given_name`, `family_name` |
| `email`   | `email`, `email_verified`                      |

Better Auth returns a claim from the table above even when its scope was not granted, if all of these are true:

* The client requests the claim through the [`claims.userinfo` parameter](https://openid.net/specs/openid-connect-core-1_0.html#IndividualClaimsRequests).
* The claim appears in `claims_supported`.
* Your [consent page](/docs/beta/plugins/oauth-provider/sign-in-flow#consent-page) did not remove the claim. It removes one when it passes a `claims` object to `oauth2.consent` that leaves the claim out.
* The user has a value for the claim. Better Auth omits missing values instead of returning `null`.
* The access token is opaque. With a JWT access token, UserInfo returns only the claims its scopes cover.

Better Auth does not fill in other requested names, such as `locale`. To return one on request, list it in `advertisedMetadata.claims_supported` together with the defaults you still want, as in [Discovery metadata](#discovery-metadata). Then read `requestedClaims` in `customUserInfoClaims`, described below.

To add claims to the [UserInfo response](https://openid.net/specs/openid-connect-core-1_0.html#UserInfoResponse), 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:

```ts title="auth.ts"
oauthProvider({
  customUserInfoClaims: ({ user, scopes, requestedClaims, jwt }) => ({ // [!code highlight]
    locale: "en-GB", // [!code highlight]
    ...(requestedClaims.includes("website") ? { website: user.website } : {}), // [!code highlight]
  }), // [!code highlight]
})
```

A returned claim replaces the standard claim of the same name, except `sub`.

## Pairwise subject identifiers [#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](https://openid.net/specs/openid-connect-core-1_0.html#SubjectIDTypes)). To let clients receive a `sub` that other clients cannot correlate, set `pairwiseSecret`:

```ts title="auth.ts"
oauthProvider({
  pairwiseSecret: process.env.PAIRWISE_SECRET, // at least 32 characters // [!code highlight]
})
```

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 client's **sector identifier** and the user ID, keyed with `pairwiseSecret` ([OIDC Core §8.1](https://openid.net/specs/openid-connect-core-1_0.html#PairwiseAlg)). Clients in different sectors always receive different `sub` values for the same user, and a client always receives the same `sub` for the same user. Better Auth assigns the sector when the client is created:

* A client whose redirect URIs all use `https` gets the host of its first redirect URI, including any port. Clients on the same `https` host share a sector, so they receive the **same** pairwise `sub`.
* Any other client gets a sector of its own. Examples are clients with an authority-free private-use redirect URI (`com.example.app:/callback`) or a loopback one (`http://localhost:8787/callback`). Any app can register a custom scheme, and any local process can listen on a loopback port, so those redirect URIs do not identify the client.

Changing a client's redirect URIs recomputes its sector, so moving to another host changes the `sub` its users receive. Clients created before Better Auth stored sectors keep the sector of their first redirect URI host, so their users' `sub` does not change. Unrelated custom-scheme or loopback clients created before then can share a sector.

* Pairwise `sub` appears in the ID token, UserInfo, and introspection. Introspection returns the `sub` of 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 a `resource` learns the real user ID. To keep the user ID from a pairwise client, have it request opaque tokens by omitting `resource`.

<Callout type="warn">
  `pairwiseSecret` must be at least 32 characters. Changing it changes every pairwise `sub` and breaks existing client accounts. Treat it as permanent.
</Callout>

`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. The host in such a URI therefore does not identify the client. Registration fails with `invalid_client_metadata` in either case.

## RP-initiated logout [#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](https://openid.net/specs/openid-connect-rpinitiated-1_0.html#RPLogout) for it:

```ts title="auth.ts"
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, // [!code highlight]
  },
});
```

* 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_hint` for 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](https://openid.net/specs/openid-connect-rpinitiated-1_0.html#RedirectionAfterLogout) only when `post_logout_redirect_uri` exactly matches one of the client's registered `post_logout_redirect_uris`, and adds `state` only to that redirect. For example, `https://app.example.com/logout/` does not match a registered `https://app.example.com/logout`. Without a matching URI, a browser shows a logged-out page from Better Auth.
* When clients registered for [front-channel logout](#front-channel-logout) must be notified, a browser gets the front-channel logout page instead. That page then redirects or shows the logged-out message.

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 [#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](https://openid.net/specs/openid-connect-backchannel-1_0.html#LogoutToken) to each client that registered a URI and holds tokens for that session:

```ts title="auth.ts"
await auth.api.adminCreateOAuthClient({
  headers,
  body: {
    redirect_uris: ["https://app.example.com/callback"],
    backchannel_logout_uri: "https://app.example.com/logout/backchannel", // [!code highlight]
    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 `resource` request without `offline_access`, is not notified.
* Logout Tokens carry `typ: logout+jwt`, always include `sid`, and live for 120 seconds. The JWT plugin signs them, so a client verifies them with your JWKS. Each [request](https://openid.net/specs/openid-connect-backchannel-1_0.html#BCRequest) has a 5 second timeout and is not retried.
* When the session is deleted, Better Auth revokes the session's access tokens and its refresh tokens without `offline_access`. This happens whether or not any client registered a `backchannel_logout_uri`. Refresh tokens with `offline_access` survive, as [§2.7](https://openid.net/specs/openid-connect-backchannel-1_0.html#BCActions) allows.
* `backchannel_logout_uri` must be a public `https` URL with no credentials or fragment. Loopback, private, and metadata hosts are rejected with `invalid_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](/docs/beta/plugins/cimd) cannot use back-channel logout.

<Callout type="warn">
  Back-channel logout requires the [JWT plugin](/docs/beta/plugins/jwt), which signs Logout Tokens. With `disableJwtPlugin: true`, registering a `backchannel_logout_uri` fails and discovery advertises `backchannel_logout_supported: false`.
</Callout>

<Callout type="info">
  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.
</Callout>

## Front-channel logout [#front-channel-logout]

[Front-Channel Logout](https://openid.net/specs/openid-connect-frontchannel-1_0.html) notifies clients through the user's browser. When a user logs out at `/oauth2/end-session`, Better Auth renders a page with one hidden iframe per client that holds tokens on the session. Each iframe loads that client's `frontchannel_logout_uri`, so the client can clear its own session cookies. As with back-channel logout, Better Auth finds these clients through the opaque access tokens and refresh tokens stored for the session. A client that holds only a JWT access token gets no iframe.

<Callout type="warn">
  The iframes are third-party content. Safari blocks third-party cookies, Firefox partitions them by default, and Chrome blocks them in Incognito and for users who turn them off. A client on a different site therefore often cannot see its session cookie inside the iframe. Front-channel logout is reliable only when your provider and its clients share a registrable domain, such as `auth.example.com` and `app.example.com`. Use [back-channel logout](#back-channel-logout) when clients run on other sites or when logout must not depend on the browser.
</Callout>

To opt a client in, register a `frontchannel_logout_uri` on the same scheme, host, and port as one of its `redirect_uris`:

```ts title="admin-create-oauth.ts"
await auth.api.adminCreateOAuthClient({
  headers,
  body: {
    redirect_uris: ["https://app.example.com/api/auth/callback"],
    enable_end_session: true,
    frontchannel_logout_uri: "https://app.example.com/logout/frontchannel", // [!code highlight]
  },
});
```

Better Auth loads the URI with `iss` and `sid` query parameters added to any query it already has, replacing a registered `iss` or `sid`. `sid` matches the `sid` claim in the ID tokens issued to that client, so the client can ignore requests that don't match its current session. The client's endpoint should clear its session state and respond with `Cache-Control: no-store`. Setting `frontchannel_logout_session_required: true` is accepted and stored, but changes nothing, because Better Auth always sends both parameters.

Better Auth validates the `frontchannel_logout_uri` at registration and on every client update:

* It must be an absolute `http` or `https` URL with no fragment and no credentials.
* An `http` URL must be on a loopback host. [`allowInsecureRedirectUri`](/docs/beta/plugins/oauth-provider/clients#http-redirect-uris) does not apply to it.
* Its scheme, host, and port must match one of the client's `redirect_uris`, as the specification requires. A URI that matches a loopback redirect URI, or an `https` redirect URI on a private network, is accepted, because the browser loads it, not the server.
* It does not require the [JWT plugin](/docs/beta/plugins/jwt), because nothing is signed.

A URI that fails validation is rejected with `invalid_client_metadata`.

### When the iframes are rendered [#when-the-iframes-are-rendered]

Better Auth renders the page only when the session actually ends during a browser navigation to `/oauth2/end-session`, either with a verified `id_token_hint` or after the user confirms logout. If a `session.delete.before` hook vetoes the deletion, no client is notified. When no front-channel client holds tokens on the session, the endpoint redirects or shows the logged-out page as before.

Front-channel logout does not run for:

* `/sign-out` or admin session revocation, because no logout page is shown in the user's browser.
* Fetch-style calls such as `authClient.oauth2.endSession()`, which keep the JSON response.
* Session expiry, which does not delete the session when it happens.

Back-channel logout still fires for the first two, because they delete the session. A client that registers both URIs receives both notifications, so make the client's logout handlers idempotent.

After the iframes load, or after 3 seconds if a client doesn't respond, the page redirects to the verified `post_logout_redirect_uri`. Without one, it shows the logged-out message. Without JavaScript, the iframes still load and a meta refresh performs the redirect.

The page keeps the same Content Security Policy as the other logout pages, extended only with `frame-src` for the client origins and its own script. It sends `Referrer-Policy: no-referrer`, so the `id_token_hint` in the URL never reaches a client.

<Callout type="info">
  Better Auth advertises `frontchannel_logout_supported: true` and `frontchannel_logout_session_supported: true` on both `.well-known/openid-configuration` and `.well-known/oauth-authorization-server`, whether or not the JWT plugin is enabled.
</Callout>

