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.
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.
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.
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:
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 withPOST /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:
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:
- The identity of the provider account: its user logs in.
- Without identity, the address must be verified by the provider:
OAUTH_EMAIL_NOT_VERIFIEDotherwise. - An address of a domain that logs in with its IdP (SSO enforcement) answers
SSO_REQUIRED, before anything is linked or created. - An account with this address: linked with
linking: 'verified_email',ACCOUNT_LINK_REQUIREDotherwise. - No account: a sign-up, with a verified address and no password, when
signUpis on and the sign-up is notclosed;SIGN_UP_DISABLEDotherwise.
Linking
A logged-in user links a provider account to the account:
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_REVOKEDand links nothing. A link started before a remediation is never finished after it. The check reads thesessionsstore, orisSessionRevoked(); 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.
The identities store
dataProvider.identities keeps an identity as { id, userId, provider, subject, email, tokens, createdAt, lastUsedAt }:
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.
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
stateand, with OpenID Connect, anonce. They live in the state cookie,dotpress_oauth_state(__Host-dotpress_oauth_statewith secure cookies, so that a sibling subdomain cannot plant its own), encrypted withsecrets.keys,HttpOnly, onPath=/, valid 10 minutes and cleared by the callback. ItsSameSiteisLax, andNone(secure) for theform_postproviders, whose callback is a cross-site POST. A state is used once, remembered in the store ofrateLimitsuntil it expires (a shared store with several instances): replayed, it answersOAUTH_STATE_INVALID. - The ID tokens come from the token endpoint over TLS, and their issuer, audience, expiration and nonce are checked.
redirectTomust matchredirects.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 withPROVIDER_UNAVAILABLE.
Errors
The callback carries the code in ?error=; the other routes answer it.