Skip to content

How To Add OAuth Login

Use this guide when you want users to sign in with an external OAuth provider while still letting Seamless Auth own local users, sessions, cookies, and auth events.

OAuth login is available through:

  • seamless-auth-api raw routes under /oauth/*
  • @seamless-auth/express adapter routes under /auth/oauth/*
  • @seamless-auth/react helpers on useAuth()

React UI
-> POST /auth/oauth/:providerId/start
-> redirect browser to provider
-> provider redirects back to your React callback route
-> POST /auth/oauth/:providerId/callback
-> backend adapter sets Seamless Auth cookies
-> React provider refreshes session state

The OAuth provider secret never belongs in browser code. The auth API reads it from an environment variable named by the provider config.


LOGIN_METHODS must include oauth.

LOGIN_METHODS=passkey,magic_link,email_otp,phone_otp,oauth

Configure providers with OAUTH_PROVIDERS. This value is a JSON array.

OAUTH_PROVIDERS=[{"id":"google","name":"Google","enabled":true,"clientId":"google-client-id.apps.googleusercontent.com","clientSecretEnv":"GOOGLE_CLIENT_SECRET","authorizationUrl":"https://accounts.google.com/o/oauth2/v2/auth","tokenUrl":"https://oauth2.googleapis.com/token","userInfoUrl":"https://openidconnect.googleapis.com/v1/userinfo","scopes":["openid","email","profile"],"redirectUris":["http://localhost:5173/oauth/callback"],"subjectJsonPath":"sub","emailJsonPath":"email","emailVerifiedJsonPath":"email_verified","nameJsonPath":"name","allowSignup":true,"accountLinking":"email","requireEmailVerified":true}]
GOOGLE_CLIENT_SECRET=replace-with-provider-secret
OAUTH_STATE_SECRET=replace-with-long-random-secret

Provider config fields:

Field Purpose
id Route identifier, such as google
name Display name returned to the UI
enabled Whether the provider is visible and usable
clientId OAuth client ID
clientSecretEnv Env var name that contains the client secret. Must end in _CLIENT_SECRET (API v0.19.4)
authorizationUrl Provider authorization endpoint
tokenUrl Provider token endpoint
userInfoUrl Provider userinfo endpoint
scopes Provider scopes sent as a space-delimited OAuth scope value
redirectUri Optional single redirect URI
redirectUris Optional allowlist of exact redirect URIs
subjectJsonPath Profile field used as provider subject, default sub
emailJsonPath Profile field used as email, default email
emailVerifiedJsonPath Profile field used for email verification, default email_verified. See Choosing A Provider
nameJsonPath Optional profile field used as display name metadata
allowSignup Whether OAuth can create a new local user
accountLinking email or disabled
requireEmailVerified Whether profile email must be verified
pkce Optional boolean
issuer OpenID Connect issuer. With jwksUri, the ID token is verified and used as the profile
jwksUri The provider’s signing keys, used to verify the ID token
externalIdSource Import source whose users a first sign-in can link to
externalIdJsonPath ID token claim holding the imported user’s external id, such as oid
promptPasskeyEnrollment Default false. When true, a user with no passkey who signs in through it gets nextStep: 'enroll_passkey'

In production, provider URLs must use https and connect only to public addresses; the server does not follow redirects from them. For an identity provider on your own network, list its host in OAUTH_PROVIDER_PRIVATE_HOSTS. Link-local addresses are refused even when listed.

In production, set OAUTH_STATE_SECRET. Development can fall back, but production should not rely on derived local state secrets.


A provider’s email decides which local account an OAuth sign-in belongs to, so only enable a provider whose verified email you are willing to treat as proof of ownership.

  • Use providers that verify the address themselves and say so in the profile, such as Google’s email_verified.
  • Point emailVerifiedJsonPath only at a claim the provider sets after verifying the address. Never point it at a field the user, or an administrator of another tenant, can set, and never at a value that is always true. That turns every profile into a verified one.
  • Keep accountLinking at disabled for a provider you do not trust to verify addresses, so it can only sign in identities it created.

Register a single-tenant application and use your tenant’s endpoints:

https://login.microsoftonline.com/<tenant-id>/oauth2/v2.0/authorize
https://login.microsoftonline.com/<tenant-id>/oauth2/v2.0/token

Then configure the provider as OpenID Connect, so the profile comes from a verified ID token:

{
"id": "microsoft",
"authorizationUrl": "https://login.microsoftonline.com/<tenant-id>/oauth2/v2.0/authorize",
"tokenUrl": "https://login.microsoftonline.com/<tenant-id>/oauth2/v2.0/token",
"userInfoUrl": "https://graph.microsoft.com/oidc/userinfo",
"issuer": "https://login.microsoftonline.com/<tenant-id>/v2.0",
"jwksUri": "https://login.microsoftonline.com/<tenant-id>/discovery/v2.0/keys",
"scopes": ["openid", "email", "profile"],
"emailVerifiedJsonPath": "xms_edov",
"externalIdSource": "entra-id",
"externalIdJsonPath": "oid"
}
  • <tenant-id> is the directory (tenant) id, a GUID. ID tokens name the tenant that way, so a domain will not match the issuer.
  • Add the xms_edov optional claim under Token configuration in the app registration. It says the tenant has verified the email’s domain, which is what lets a Microsoft sign-in link to or create an account by email.
  • externalIdSource and externalIdJsonPath link users you imported from Entra ID (with seamless migrate and source entra-id) by their object id, so they sign in to the right account without relying on email.
  • Add "promptPasskeyEnrollment": true while users are moving off the directory, so the callback answers nextStep: 'enroll_passkey' for a user who signs in through it without a passkey. See Migrate Users.

Do not use common, organizations, or consumers. They accept a sign-in from any Entra tenant, and the administrator of each tenant controls the email address its users present. seamless init --oauth asks for your directory (tenant) id and refuses those three values.


The redirect URI passed to startOAuthLogin(...) must be allowed by the provider config.

If redirectUris or redirectUri is set, the requested redirect URI must exactly match one of those values. If no provider redirect allowlist is set, the auth API falls back to the configured Seamless Auth origins.

For local React development, the built-in callback route is:

http://localhost:5173/oauth/callback

That URI must also be registered with the external OAuth provider, and must appear in the provider’s redirectUris allowlist above.

A custom scheme such as myapp://oauth/callback has no origin, so it never passes the fallback to Seamless Auth origins. It must be listed in redirectUris, and a start that asks for it otherwise answers 400 and records oauth_login_failed with reason start_failed and detail redirect_not_allowed.

Listing it satisfies Seamless Auth only. The provider has to accept it as well, and Google does not take a custom scheme on the web application client that a server-side token exchange uses: its web server guide requires https redirect URIs apart from localhost, and its native app guide says custom URI schemes are no longer supported on Android. With Google, register an https page you serve and have that page pass code and state on to the app’s scheme. Test the whole trip on a device before offering the button.


Use listOAuthProviders() so your UI follows the server config.

import { useEffect, useState } from 'react'
import { useAuth, type OAuthProvider } from '@seamless-auth/react'
export function OAuthButtons() {
const { listOAuthProviders, startOAuthLogin } = useAuth()
const [providers, setProviders] = useState<OAuthProvider[]>([])
const [message, setMessage] = useState<string | null>(null)
useEffect(() => {
void listOAuthProviders().then(({ data, error }) => {
if (error) {
setMessage(error.message)
return
}
setProviders(data.providers)
})
}, [listOAuthProviders])
async function start(provider: OAuthProvider) {
// Remember which provider so the callback can finish the right flow.
sessionStorage.setItem('seamless:oauth:provider', provider.id)
const { data, error } = await startOAuthLogin({
providerId: provider.id,
redirectUri: `${window.location.origin}/oauth/callback`,
returnTo: `${window.location.origin}/dashboard`,
})
if (error) {
setMessage(error.message)
return
}
window.location.assign(data.authorizationUrl)
}
return (
<div>
{providers.map((provider) => (
<button key={provider.id} onClick={() => void start(provider)}>
Continue with {provider.name}
</button>
))}
{message && <p>{message}</p>}
</div>
)
}

Both helpers resolve to { data, error } (see Reading Results). The provider list is data.providers and the provider’s sign-in URL is data.authorizationUrl.

returnTo must be a full URL. The auth API only preserves it when its origin is allowed by the configured origins.


Create a React route that matches the redirectUri you sent in Step 3:

<Route path="/oauth/callback" element={<OAuthCallback />} />

Then finish the login from the callback page. The provider id was stashed in sessionStorage during Step 3, and the code and state come back on the URL.

import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useAuth } from '@seamless-auth/react'
export function OAuthCallback() {
const { finishOAuthLogin } = useAuth()
const navigate = useNavigate()
const [error, setError] = useState<string | null>(null)
useEffect(() => {
async function finish() {
const params = new URLSearchParams(window.location.search)
const code = params.get('code')
const state = params.get('state')
const providerId = sessionStorage.getItem('seamless:oauth:provider')
if (!providerId || !code || !state) {
setError('OAuth callback is missing required values.')
return
}
const result = await finishOAuthLogin({ providerId, code, state })
sessionStorage.removeItem('seamless:oauth:provider')
if (result.error) {
setError(result.error.message)
return
}
navigate('/dashboard', { replace: true })
}
void finish()
}, [finishOAuthLogin, navigate])
if (error) return <p>{error}</p>
return <p>Signing you in...</p>
}

finishOAuthLogin never throws. A failed callback (an expired state, a provider that refuses the code, an unverified email) resolves to a result with error set, so a try/catch around it would fall through to navigate('/dashboard') and send a signed-out user into the app. Check error and return before navigating. On success the provider refreshes its session before the promise resolves, so useAuth() is already signed in when the dashboard renders.

The snippet reads result.error instead of destructuring because the component already has an error state variable.

Since auth API 0.19.2 the callback must also carry the binding that /start returned, which ties the state to the browser that started the sign-in. startOAuthLogin and finishOAuthLogin from useAuth() keep it in sessionStorage and send it for you (@seamless-auth/client 0.7.1 and later), so the snippets above need no change. If you call the auth client directly instead, keep data.binding from the start response with its state and pass it as binding to finishOAuthLogin. A callback without it fails with Invalid OAuth state.

When the Express adapter handles /auth/oauth/:providerId/callback, it verifies the auth API response and sets the access and refresh cookies.


OAuth identity rows link a provider subject to a local user.

The current auth API behavior is:

Case Behavior
Existing oauth_identities row Reuse the linked local user
No identity, matching user email, accountLinking: "email", email verified Link provider identity to that user
No identity, matching user email, accountLinking: "disabled" Reject login
No matching user, allowSignup: true, email verified Create a verified local user with default roles
No matching user, allowSignup: false Reject login
No identity yet and the provider does not assert the email is verified Reject with oauth_email_not_verified

The profile email must exist. Linking to an existing account and creating a new one both require the provider to assert the email is verified (email_verified: true, read from emailVerifiedJsonPath), whatever requireEmailVerified is set to. An identity that is already linked keeps signing in. A provider whose profile has no verification claim, such as Microsoft Graph’s userinfo, can sign in identities it already linked but cannot link or create new ones.

GitHub’s /user has no verification claim either, so a GitHub provider (a userInfoUrl of https://api.github.com/user, or GitHub Enterprise Server’s /api/v3/user) also reads /user/emails and uses the address GitHub lists as verified. Request the user:email scope.

When a verified provider email links to an account that had not yet proven its address (one an admin created or imported), the account is marked verified, and a phone verified before then is removed.


Symptom Likely cause
Provider does not appear LOGIN_METHODS does not include oauth, provider is disabled, or config failed validation
OAuth start returns 400 redirectUri is not in the provider allowlist
Provider rejects redirect Provider console does not include the same redirect URI
Callback returns Invalid OAuth state State expired, wrong provider ID, or OAUTH_STATE_SECRET changed mid-flow
Callback returns OAuth signup is disabled No matching local user and allowSignup is false
Callback returns oauth_invalid_id_token The ID token failed verification: wrong issuer or jwksUri, a clock far out of sync, or a reused sign-in
Callback returns oauth_email_not_verified The provider did not assert the email is verified, and this identity is not linked yet
Callback succeeds but React still looks signed out Callback did not hit the backend adapter, cookies were blocked, or refreshSession() did not run

  • Keep provider client secrets in environment variables.
  • Enable only providers that verify email addresses, and scope Microsoft to your tenant. See Choosing A Provider.
  • Use exact redirect URI allowlists for production providers.
  • Set a stable OAUTH_STATE_SECRET in production.
  • Treat OAuth as authentication only; app authorization still belongs in your backend.
  • Keep APP_ORIGINS, ORIGINS, cookie domain, and provider redirect URIs aligned.