> For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt.

# Social login (OAuth)

`oauth` adds the login with Google, GitHub, Microsoft, Apple, or any OpenID Connect or OAuth 2 provider, and the provider accounts linked to the users (the identities). It talks to the providers with `oauth4webapi`, an optional peer dependency, and needs `secrets.keys` (the state of a flow is encrypted), `redirects.allowed` (the pages the flows end on), `rateLimits` (its store remembers the states already used), and the `identities`, `users.findByEmail()`, `users.findAccount()`, with sign-up `users.create()`, and with `linking: 'verified_email'` `users.setPasswordHash()`, `users.markEmailVerified()` and the delete methods of the optional stores the data provider has (`passkeys.list()` and `delete()`, `identities.listByUser()` and `delete()`, `mfa.listFactors()`, `deleteFactor()` and `deleteRecoveryCodes()`, `trustedDevices.revokeAll()`) [stores](https://dotpress.dev/auth/data-provider.md#the-stores).

```bash
pnpm add oauth4webapi
```

```ts
import { createGitHubProvider, createGoogleProvider, createOAuth } from '@dotpress/auth/oauth'

createAuth({
  // …
  secrets: { keys: [{ id: '1', key: process.env.SECRET_KEY }] },
  redirects: { allowed: ['https://app.example.com'] },
  oauth: createOAuth({
    redirectBaseUrl: 'https://api.example.com/auth',
    providers: [
      createGoogleProvider({ clientId: process.env.GOOGLE_CLIENT_ID, clientSecret: process.env.GOOGLE_CLIENT_SECRET }),
      createGitHubProvider({ clientId: process.env.GITHUB_CLIENT_ID, clientSecret: process.env.GITHUB_CLIENT_SECRET }),
    ],
  }),
})
```

| Option            | Default      | Description                                                                                                                                                                                                                                                |
| ----------------- | ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `providers`       | —            | The providers, created by the factories below, with distinct ids. Required.                                                                                                                                                                                |
| `redirectBaseUrl` | —            | Public URL of the auth routes, like `https://api.example.com/auth`: `https`, or `http` for `localhost` and `127.0.0.1` only; no query nor hash. Required.                                                                                                  |
| `signUp`          | `true`       | New users sign up through the providers. `signUp.mode: 'closed'` of the [sign-up](https://dotpress.dev/auth/sign-up.md) also turns it off.                                                                                                                 |
| `linking`         | `'explicit'` | What a login does with the verified address of an existing account: `'explicit'` refuses it (`ACCOUNT_LINK_REQUIRED`), the user links the provider from a session; `'verified_email'` links it, and claims an unverified account. See [Linking](#linking). |
| `storeTokens`     | `false`      | Keeps the tokens of the providers, encrypted. See [Provider tokens](#provider-tokens).                                                                                                                                                                     |

`createOAuth()` and the provider factories throw a `TypeError` for an invalid or unknown option, at startup. `createAuth()` throws without `secrets.keys` or `redirects.allowed`, and with `rateLimits: false`: turn the limits off one by one instead (`rateLimits: { oauth: { ip: false, callbackIp: false } }`).

## Providers

Register the callback URL `<redirectBaseUrl>/oauth/<provider>/callback` at the provider: `https://api.example.com/auth/oauth/google/callback`.

| Factory                     | Id          | Options                                                                                             | Notes                                                                                                                                                                                                                                                                                                                                                           |
| --------------------------- | ----------- | --------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `createGoogleProvider()`    | `google`    | `clientId`, `clientSecret`, `scopes?`                                                               | OpenID Connect. The address is verified with the `email_verified` claim.                                                                                                                                                                                                                                                                                        |
| `createMicrosoftProvider()` | `microsoft` | `clientId`, `clientSecret`, `tenant?`, `scopes?`                                                    | Microsoft Entra ID, OpenID Connect. `tenant`: `common` (default: work, school and personal accounts), `organizations`, `consumers`, or a directory (tenant) ID. The multi-tenant endpoints check the issuer of each ID token against its tenant (`tid`). The address is verified only with the `xms_edov` optional claim: configure it in the app registration. |
| `createAppleProvider()`     | `apple`     | `clientId` (the Services ID), `teamId`, `keyId`, `privateKey` (the `.p8` PKCS#8 PEM key), `scopes?` | Sign in with Apple. Apple posts the callback (`form_post`) and gives the name of the user on the first login only. The client secret is a JWT signed with the key at each token request.                                                                                                                                                                        |
| `createGitHubProvider()`    | `github`    | `clientId`, `clientSecret`, `scopes?`                                                               | OAuth 2: the profile and the addresses come from the GitHub API. Default scopes `read:user user:email`.                                                                                                                                                                                                                                                         |
| `createOidcProvider()`      | `id`        | `id`, `issuer`, `clientId`, `clientSecret?`, `scopes?`, `trustEmailVerified?`                       | Any OpenID Connect provider (Okta, Auth0, Keycloak, GitLab…), discovered from `<issuer>/.well-known/openid-configuration`. Without `clientSecret`, a public client with PKCE only. `trustEmailVerified: false` treats every address as unverified.                                                                                                              |
| `createOAuth2Provider()`    | `id`        | `id`, `authorizationEndpoint`, `tokenEndpoint`, `clientId`, `clientSecret?`, `scopes`, `profile`    | A plain OAuth 2 provider: `profile({ accessToken, fetch })` reads the account from its API and returns `{ subject, email?, emailVerified?, name?, picture? }`.                                                                                                                                                                                                  |

The OpenID Connect providers ask `openid email profile` by default, and their `scopes` must include `openid`; Apple asks `name email`. An `id` has lowercase letters, digits and `-`. Every factory takes a `fetch` option, for a proxy or the tests.

```ts
const discord = createOAuth2Provider({
  id: 'discord',
  authorizationEndpoint: 'https://discord.com/oauth2/authorize',
  tokenEndpoint: 'https://discord.com/api/oauth2/token',
  clientId: process.env.DISCORD_CLIENT_ID,
  clientSecret: process.env.DISCORD_CLIENT_SECRET,
  scopes: ['identify', 'email'],
  profile: async ({ accessToken, fetch }) => {
    const response = await fetch('https://discord.com/api/users/@me', {
      headers: { authorization: `Bearer ${accessToken}` },
    })
    const user = await response.json()
    return { subject: user.id, email: user.email, emailVerified: user.verified }
  },
})
```

`emailVerified` defaults to `false`: return `true` only for an address the provider verified, since a verified address can log in to the account that owns it.

## Login

A link to the start route begins the flow:

```html
<a href="https://api.example.com/auth/oauth/google/start?redirectTo=https://app.example.com/home">Continue with Google</a>
```

| Route                                 | Query or body                    | Answer                                                                                                                                                                                                                                                                                                                                                            |
| ------------------------------------- | -------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `GET /auth/oauth/:provider/start`     | `?redirectTo&mode&codeChallenge` | `302` to the provider. 30 per 15 minutes per IP (`rateLimits.oauth.ip`). With `mode=body` and `handoff.pkce: 'required'`, `400 CODE_CHALLENGE_REQUIRED` without a valid `codeChallenge`.                                                                                                                                                                          |
| `GET /auth/oauth/:provider/callback`  | The parameters of the provider   | `302` to `redirectTo`. The callbacks without a valid state (missing, invalid, expired or already used) count against 30 per 15 minutes per IP (`rateLimits.oauth.callbackIp`), then answer `429 TOO_MANY_REQUESTS`; the callbacks of valid flows are not counted, so that clients sharing an address (no `getIp` behind a proxy) never block each other's logins. |
| `POST /auth/oauth/:provider/callback` | The form of the provider         | The same, for the `form_post` providers (Apple)                                                                                                                                                                                                                                                                                                                   |

`redirectTo` must match `redirects.allowed`; otherwise the flow ends on the first allowed URL. A flow lasts 10 minutes. The callback redirects to `redirectTo` with:

- the auth cookies (`mode=cookie`);
- `?challenge=<challengeToken>`: the user has a second factor, to verify with `POST /auth/mfa/verify` (see [MFA](https://dotpress.dev/auth/mfa.md));
- `?code=<code>`: a [handoff code](https://dotpress.dev/auth/magic-link.md#handoff-codes) (`mode=body`);
- `?linked=<provider>`: a [link](#linking) succeeded;
- `?error=<CODE>`: the flow failed, like `?error=ACCOUNT_LINK_REQUIRED`. An invalid, expired or already used state ends on the first allowed URL with `?error=OAUTH_STATE_INVALID`. A link whose session ended meanwhile ends with `?error=SESSION_REVOKED`.

The page that reads `?challenge=` or `?code=` removes it from the address bar (`history.replaceState()`): the history and the `Referer` of the next requests keep no copy.

`mode` is `cookie` with the [cookie mode](https://dotpress.dev/auth/cookies.md), `body` with [`handoff`](https://dotpress.dev/auth/magic-link.md#handoff-codes); it defaults to `cookie` when both are on. Without either, the start route is not registered. In body mode, the client exchanges the code for the tokens, with its PKCE verifier as `handoff.pkce` requires:

```ts
const verifier = randomVerifier()
location.href = `${api}/auth/oauth/google/start?mode=body&redirectTo=${app}/callback&codeChallenge=${await s256(verifier)}`

// on /callback?code=…
const tokens = await post('/auth/token', { code, codeVerifier: verifier })
```

The session has the method `oauth` and the `amr` `fed`. The account gate, `beforeSession` and [MFA](https://dotpress.dev/auth/mfa.md) apply as for a password login, [trusted devices](https://dotpress.dev/auth/mfa.md#trusted-devices) included.

A login resolves its user in this order:

1. The identity of the provider account: its user logs in.
2. Without identity, the address must be verified by the provider: `OAUTH_EMAIL_NOT_VERIFIED` otherwise.
3. An address of a domain that logs in with its IdP ([SSO enforcement](https://dotpress.dev/auth/sso.md#discovery-and-enforcement)) answers `SSO_REQUIRED`, before anything is linked or created.
4. An account with this address: linked with `linking: 'verified_email'`, `ACCOUNT_LINK_REQUIRED` otherwise.
5. No account: a sign-up, with a verified address and no password, when `signUp` is on and the [sign-up](https://dotpress.dev/auth/sign-up.md) is not `closed`; `SIGN_UP_DISABLED` otherwise.

## Linking

A logged-in user links a provider account to the account:

| Route                             | Body              | Answer                                                                                                         |
| --------------------------------- | ----------------- | -------------------------------------------------------------------------------------------------------------- |
| `POST /auth/oauth/:provider/link` | `{ redirectTo? }` | `{ url }`: the page of the provider to open. The callback redirects to `redirectTo` with `?linked=<provider>`. |
| `GET /auth/identities`            | —                 | `{ identities }`: `id`, `provider`, `email`, `createdAt`, `lastUsedAt`                                         |
| `DELETE /auth/identities/:id`     | —                 | `{ status: 'removed' }`                                                                                        |

The link and the removal require an authentication of less than 10 minutes (`403 REAUTHENTICATION_REQUIRED`, see [step-up](https://dotpress.dev/auth/step-up.md)), and refuse [impersonations](https://dotpress.dev/auth/sessions.md#impersonation). The link request sets the state cookie: send it with the credentials of the API.

- A provider account linked to another user answers `?error=IDENTITY_ALREADY_LINKED`.
- The link belongs to the session that started it: when that session is revoked or ended before the callback (logout, password reset or change, `revokeUserSessions()`), the callback answers `?error=SESSION_REVOKED` and links nothing. A link started before a remediation is never finished after it. The check reads the `sessions` store, or `isSessionRevoked()`; without either, a revocation is not seen, and the link stays possible for the 10 minutes of its state.
- The last way to log in of an account (no password, no passkey, no other identity) cannot be removed: `409 LAST_LOGIN_METHOD`.
- An unknown identity, or an identity of another user, answers `404 IDENTITY_NOT_FOUND`.

`linking: 'verified_email'` links at login the provider account to the account of its verified address. It trusts the providers with the accounts: keep `'explicit'` unless every provider verifies the addresses it gives. The link also claims an unverified account, like a [magic link](https://dotpress.dev/auth/magic-link.md#unverified-accounts): its password is removed, its sessions are revoked (reason `account_claimed`), its passkeys, linked identities, second factors, recovery codes and trusted devices are removed, its pending links are invalidated, and its address becomes verified. Someone who signed up with the address of another person loses the account, and every way in set up before, when that person logs in with the provider.

## Provider tokens

With `storeTokens`, the identity keeps the tokens of the provider, `{ accessToken, refreshToken?, expiresAt?, scope? }`, as JSON encrypted with `secrets.keys`, renewed at each login: the app calls the API of the provider with them. Ask the scopes it needs in `scopes`.

`auth.oauth.identities.tokens({ userId, identityId })` returns the decrypted tokens of an identity of the user, or `undefined` without stored tokens. The encrypted value is bound to its identity: copied to another row, it does not decrypt.

```ts
const tokens = await auth.oauth.identities.tokens({ userId: ctx.user.id, identityId })
if (tokens) await fetch('https://api.github.com/user/repos', { headers: { authorization: `Bearer ${tokens.accessToken}` } })
```

## The identities store

`dataProvider.identities` keeps an identity as `{ id, userId, provider, subject, email, tokens, createdAt, lastUsedAt }`:

```ts
interface IdentityStore {
  find(input: { provider: string; subject: string }): Promise<StoredIdentity | undefined>
  listByUser(userId: string): Promise<StoredIdentity[]> // oldest first
  create(identity: NewIdentity): Promise<{ id: string } | 'taken'> // 'taken': provider account already linked
  update(id: string, patch: { lastUsedAt: Date; email: string | null; tokens?: string | null }): Promise<void>
  delete(id: string): Promise<void>
}
```

`subject` is the account id at the provider. Put a unique constraint on `provider` and `subject`. `email` is the address given at the last login; `tokens` is `null` without `storeTokens`.

## Services

`auth.oauth.start({ provider, mode, redirectTo?, codeChallenge?, linkUserId?, linkSessionId? })` returns the authorization URL and the encrypted state (`linkUserId` and `linkSessionId`, given together, start a link of that user from that session), `auth.oauth.callback({ provider, parameters, state, meta?, trustedDeviceToken?, onInvalidState? })` ends a flow (`onInvalidState` runs before `OAUTH_STATE_INVALID`: the routes count `rateLimits.oauth.callbackIp` there), and `auth.oauth.identities.list(userId)`, `identities.unlink({ userId, identityId })` and `identities.tokens({ userId, identityId })` manage the identities, outside the routes. They throw an `AuthError`.

## In tests

`createFakeOidcProvider()` of `@dotpress/auth/testing` is an OpenID Connect provider in memory, without network: its `fetch` serves the discovery, the keys and the token endpoint, and `authorize()` plays the consent of a user.

```ts
import { createOAuth, createOidcProvider } from '@dotpress/auth/oauth'
import { createFakeOidcProvider } from '@dotpress/auth/testing'

const idp = createFakeOidcProvider({ clientSecret: 'secret' })
const oauth = createOAuth({
  redirectBaseUrl: 'http://localhost/auth',
  providers: [createOidcProvider({ id: 'idp', issuer: idp.issuer, clientId: 'client', clientSecret: 'secret', fetch: idp.fetch })],
})

const started = await fetch('/auth/oauth/idp/start?redirectTo=https://app.example.com', { redirect: 'manual' })
// The state cookie of the flow, sent back to the callback.
const stateCookie = started.headers.getSetCookie()[0]!.split(';')[0]!
const parameters = idp.authorize(started.headers.get('location')!, { subject: 'u1', email: 'ada@example.com' })
const res = await fetch(`/auth/oauth/idp/callback?${parameters}`, {
  redirect: 'manual',
  headers: { cookie: stateCookie },
})
```

`authorize()` also takes `emailVerified`, `name`, `claims`, and `error` (a refused consent, like `access_denied`); `nonce` and `state` forge an invalid answer. `setUnavailable(true)` makes every endpoint answer `503`.

## Security

- Every flow uses PKCE, a `state` and, with OpenID Connect, a `nonce`. They live in the state cookie, `dotpress_oauth_state` (`__Host-dotpress_oauth_state` with secure cookies, so that a sibling subdomain cannot plant its own), encrypted with `secrets.keys`, `HttpOnly`, on `Path=/`, valid 10 minutes and cleared by the callback. Its `SameSite` is `Lax`, and `None` (secure) for the `form_post` providers, whose callback is a cross-site POST. A state is used once, remembered in the store of `rateLimits` until it expires (a shared store with several instances): replayed, it answers `OAUTH_STATE_INVALID`.
- The ID tokens come from the token endpoint over TLS, and their issuer, audience, expiration and nonce are checked.
- `redirectTo` must match `redirects.allowed`: the flows never end on another site.
- An address is trusted only when the provider verified it, and only links an existing account with `linking: 'verified_email'`. An address of an enforced SSO domain never links nor signs up.
- A provider that does not answer, or answers a `5xx`, fails the flow with `PROVIDER_UNAVAILABLE`.

## Errors

The callback carries the code in `?error=`; the other routes answer it.

| Status | Code                       | When                                                                                           |
| ------ | -------------------------- | ---------------------------------------------------------------------------------------------- |
| `400`  | `OAUTH_STATE_INVALID`      | A missing, expired, already used or foreign state cookie                                       |
| `400`  | `CODE_CHALLENGE_REQUIRED`  | `mode=body` without `codeChallenge`, with `handoff.pkce: 'required'`                           |
| `403`  | `SSO_REQUIRED`             | The address of an enforced SSO domain, with `data.connectionId`                                |
| `429`  | `TOO_MANY_REQUESTS`        | Over `rateLimits.oauth.ip`, or `rateLimits.oauth.callbackIp` (callbacks without a valid state) |
| `401`  | `SESSION_REVOKED`          | A link whose session was revoked or ended before the callback                                  |
| `401`  | `OAUTH_FAILED`             | A refused consent, or an invalid answer of the provider                                        |
| `403`  | `OAUTH_EMAIL_NOT_VERIFIED` | A new provider account without verified address                                                |
| `409`  | `ACCOUNT_LINK_REQUIRED`    | An account uses the address, with `linking: 'explicit'`                                        |
| `409`  | `IDENTITY_ALREADY_LINKED`  | The provider account is linked to another user                                                 |
| `403`  | `SIGN_UP_DISABLED`         | A new user, with `signUp: false` or a closed sign-up                                           |
| `404`  | `IDENTITY_NOT_FOUND`       | An unknown identity, or an identity of another user                                            |
| `409`  | `LAST_LOGIN_METHOD`        | The last way to log in of the account                                                          |
| `503`  | `PROVIDER_UNAVAILABLE`     | The provider does not answer                                                                   |
