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, and this page is available as Markdown at https://dotpress.dev/auth/oauth.md.

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.

pnpm add oauth4webapi
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 }),
    ],
  }),
})
OptionDefaultDescription
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.
signUptrueNew users sign up through the providers. signUp.mode: 'closed' of the sign-up 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.
storeTokensfalseKeeps the tokens of the providers, encrypted. See 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.

FactoryIdOptionsNotes
createGoogleProvider()googleclientId, clientSecret, scopes?OpenID Connect. The address is verified with the email_verified claim.
createMicrosoftProvider()microsoftclientId, 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()appleclientId (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()githubclientId, clientSecret, scopes?OAuth 2: the profile and the addresses come from the GitHub API. Default scopes read:user user:email.
createOidcProvider()idid, 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()idid, authorizationEndpoint, tokenEndpoint, clientId, clientSecret?, scopes, profileA 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.

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:

<a href="https://api.example.com/auth/oauth/google/start?redirectTo=https://app.example.com/home">Continue with Google</a>
RouteQuery or bodyAnswer
GET /auth/oauth/:provider/start?redirectTo&mode&codeChallenge302 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/callbackThe parameters of the provider302 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/callbackThe form of the providerThe 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);
  • ?code=<code>: a handoff code (mode=body);
  • ?linked=<provider>: a link 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, body with handoff; 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:

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 apply as for a password login, 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) 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 is not closed; SIGN_UP_DISABLED otherwise.

Linking

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

RouteBodyAnswer
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), and refuse impersonations. 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: 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.

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 }:

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.

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.

StatusCodeWhen
400OAUTH_STATE_INVALIDA missing, expired, already used or foreign state cookie
400CODE_CHALLENGE_REQUIREDmode=body without codeChallenge, with handoff.pkce: 'required'
403SSO_REQUIREDThe address of an enforced SSO domain, with data.connectionId
429TOO_MANY_REQUESTSOver rateLimits.oauth.ip, or rateLimits.oauth.callbackIp (callbacks without a valid state)
401SESSION_REVOKEDA link whose session was revoked or ended before the callback
401OAUTH_FAILEDA refused consent, or an invalid answer of the provider
403OAUTH_EMAIL_NOT_VERIFIEDA new provider account without verified address
409ACCOUNT_LINK_REQUIREDAn account uses the address, with linking: 'explicit'
409IDENTITY_ALREADY_LINKEDThe provider account is linked to another user
403SIGN_UP_DISABLEDA new user, with signUp: false or a closed sign-up
404IDENTITY_NOT_FOUNDAn unknown identity, or an identity of another user
409LAST_LOGIN_METHODThe last way to log in of the account
503PROVIDER_UNAVAILABLEThe provider does not answer