Providers
Sign in your users with Google, Microsoft, GitHub, Discord, Apple or any OpenID Connect provider.
Overview
Light-Auth embeds its own OAuth 2.0 / OpenID Connect client, built on oauth4webapi and jose. Providers are created with factory functions exported by @light-auth/core, and given to CreateLightAuth:
import { CreateLightAuth } from "@light-auth/nextjs";
import { createGitHubProvider, createGoogleProvider } from "@light-auth/core";
const googleProvider = createGoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID!,
clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
});
const githubProvider = createGitHubProvider({
clientId: process.env.GITHUB_CLIENT_ID!,
clientSecret: process.env.GITHUB_CLIENT_SECRET!,
});
export const { providers, handlers, signIn, signOut, getAuthSession, getUser } = CreateLightAuth({
providers: [googleProvider, githubProvider],
});arctic property is rejected with an explicit error. Coming from a previous version? Follow the migration guide.Built-in providers
| Factory | Provider | providerName | Default scopes | Notes |
|---|---|---|---|---|
| createGoogleProvider | Google (OpenID Connect) | openid, profile, email | Set accessType: "offline" to get a refresh token. | |
| createMicrosoftEntraIdProvider | Microsoft Entra ID (OpenID Connect) | microsoft | openid, profile, email | tenant defaults to "common". Add the offline_access scope to get a refresh token. |
| createGitHubProvider | GitHub (OAuth 2.0) | github | read:user, user:email | Uses the primary verified email when the public email is hidden. |
| createDiscordProvider | Discord (OAuth 2.0) | discord | identify, email | Avatar resolved from the Discord CDN. |
| createAppleProvider | Sign in with Apple (OpenID Connect) | apple | name, email | teamId, keyId and privateKey instead of a client secret. Requires HTTPS. |
| createOidcProvider | Any OpenID Connect provider | (required) | openid, profile, email | Endpoints discovered from the issuer. |
| createOAuth2Provider | Any OAuth 2.0 provider | (required) | none | Explicit endpoints and a getProfile function. |
Every factory takes a clientId, a clientSecret, an optional redirectUri and optional scopes, added to the default ones. All the other options can be overridden as well, see Options.
Callback URL
After the sign in, the provider redirects the user to the callback URL of your application, which must be registered in the provider console. By default, the callback URL is computed from the LIGHT_AUTH_URL environment variable, the base path and the provider name:
# ${LIGHT_AUTH_URL}${basePath}/callback/${providerName}
LIGHT_AUTH_URL=http://localhost:3000
# callback URLs to register:
# http://localhost:3000/api/auth/callback/google
# http://localhost:3000/api/auth/callback/githubYou can also set the callback URL explicitly with the redirectUri option of each provider.
LIGHT_AUTH_URL (or a redirectUri) is required: Light-Auth never builds the callback URL from the request Host header, which can be spoofed. Without it, the sign in fails with "light-auth: provider google has no redirectUri, set it or define the LIGHT_AUTH_URL environment variable".Configuring each provider
import { createGoogleProvider } from "@light-auth/core";
export const googleProvider = createGoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID!,
clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
// optional: get a refresh token, to refresh the access token automatically
accessType: "offline",
// optional: scopes added to "openid", "profile" and "email"
scopes: ["https://www.googleapis.com/auth/calendar.readonly"],
});Google only returns a refresh token on the first consent. Add searchParams: new Map([["prompt", "consent"]]) to show the consent screen, and get a refresh token, on every sign in.
Options
The factories accept all the options of an OAuth provider (LightAuthOAuthProvider). The presets set the right values for you, but you can override any of them:
| Option | Type | Description |
|---|---|---|
| providerName | string | Optional Name of the provider, used in the URLs (/login/:providerName, /callback/:providerName). The presets define a default value, override it to register the same provider twice. |
| clientId | string | Required OAuth client identifier. |
| clientSecret | string | () => string | Promise<string> | Optional OAuth client secret, or a function returning it (Apple uses a short-lived signed JWT). |
| redirectUri | string | Optional Callback URL registered at the provider. Default: ${LIGHT_AUTH_URL}${basePath}/callback/${providerName}. |
| scopes | string[] | Optional Scopes requested to the provider, added to the default scopes of the factory. |
| searchParams | Map<string, string> | Optional Additional parameters of the authorization URL (e.g. prompt=consent). The parameters handled by Light-Auth (state, nonce, redirect_uri, code_challenge...) can't be overridden. |
| headers | Map<string, string> | Optional Headers sent to the token, userinfo and revocation endpoints, and to the APIs called by getProfile. |
| pkce | boolean | Optional Use PKCE (S256). Default: true. |
| responseMode | "query" | "form_post" | Optional How the provider sends the authorization response. form_post responses are posted to the callback URL from the provider domain. |
| clientAuthentication | "client_secret_basic" | "client_secret_post" | "none" | Optional How the client authenticates on the token and revocation endpoints. Default: client_secret_basic, or none without client secret. |
| issuer | string | Optional OpenID Connect issuer. Endpoints are discovered from ${issuer}/.well-known/openid-configuration and the id_tokens are validated. |
| authorizationEndpoint, tokenEndpoint, userInfoEndpoint, revocationEndpoint, jwksUri | string | Optional Explicit endpoints, they take precedence over the discovered ones. |
| getProfile | (context) => LightAuthUserClaims | Optional Maps the provider identity to the Light-Auth claims (sub, email, name, picture). Default: the validated id_token claims, or the userinfo endpoint response. |
| revokeToken | ({ token, tokenTypeHint }) => Promise<void> | Optional Revokes a token for providers that do not implement RFC 7009. Default: the revocation endpoint, if any. |
| getIdTokenIssuer | (claims) => string | Optional Expected id_token issuer, for providers whose issuer depends on the signed-in tenant. |
| onGetOAuth2Tokens | (tokens, metadata) => LightAuthTokens | Optional Called with the tokens returned by the provider, at sign in and on each refresh. Return the (modified) tokens. |
User profile and id_token claims
Once the authorization code is exchanged, Light-Auth gets the identity of the user:
- with the
getProfilefunction of the provider, if any, - otherwise from the id_token claims (OpenID Connect providers),
- otherwise from the userinfo endpoint (OAuth 2.0 providers).
The sub claim becomes the providerUserId of the session and of the user, along with email, name and picture. The sign in fails if the provider does not return a user identifier.
The getProfile function receives a context with the tokens, a fetchUserInfo() function calling the userinfo endpoint, a fetchResource(url) function calling any API of the provider with the access token, and the callbackParameters received on the callback.
Using the id_token claims
The OpenID Connect id_tokens are fully validated (signature against the provider keys, issuer, audience, expiration and nonce). Their claims are then available in the tokens.idTokenClaims property given to the onSessionSaving and onUserSaving hooks, to add your own properties:
export const { handlers, signIn, signOut, getAuthSession, getUser } = CreateLightAuth<MyLightAuthSession, MyLightAuthUser>({
providers: [googleProvider],
onSessionSaving: async (session, tokens) => {
const claims = tokens?.idTokenClaims;
if (typeof claims?.given_name === "string") session.firstName = claims.given_name;
if (typeof claims?.family_name === "string") session.lastName = claims.family_name;
return session;
},
});The tokens object (LightAuthTokens) is a plain object:
type LightAuthTokens = {
accessToken: string;
tokenType: string; // usually "bearer"
accessTokenExpiresAt?: Date;
refreshToken?: string;
idToken?: string; // raw OpenID Connect id_token (JWT)
idTokenClaims?: Record<string, unknown>; // only set once the id_token has been validated
scopes?: string[]; // granted scopes, when returned by the provider
raw: Record<string, unknown>; // raw token endpoint response
};Same provider, several configurations
The providerName identifies each provider in the URLs. Override it to register the same provider more than once, for example two Microsoft Entra ID tenants:
const contosoProvider = createMicrosoftEntraIdProvider({
providerName: "contoso", // callback URL: /api/auth/callback/contoso
tenant: "contoso.onmicrosoft.com",
clientId: process.env.CONTOSO_CLIENT_ID!,
clientSecret: process.env.CONTOSO_CLIENT_SECRET!,
});
const fabrikamProvider = createMicrosoftEntraIdProvider({
providerName: "fabrikam", // callback URL: /api/auth/callback/fabrikam
tenant: "fabrikam.onmicrosoft.com",
clientId: process.env.FABRIKAM_CLIENT_ID!,
clientSecret: process.env.FABRIKAM_CLIENT_SECRET!,
});Email & password
Besides OAuth providers, Light-Auth supports a credentials provider, to sign in your users with an email and a password stored in your own database. Both kinds of providers can be used together. See Email & Password.
Security
- Each sign in uses a random
state, a PKCE code verifier (S256) and, for OpenID Connect providers, anonce. They are kept in short-lived (10 minutes) HTTP-only cookies until the callback. - The id_token signature is verified against the provider JSON Web Key Set, along with its issuer, audience, expiration and nonce.
- The access and refresh tokens are stored server-side only, and are never sent to the browser.
- The requests to the provider time out after 10 seconds.
More details in Security.