Skip to Content

OAuth

Learn how to configure social OAuth providers, sign in and link accounts, request scopes, pass additional data, refresh access tokens, map profiles, and customize provider options.

Entro Auth comes with built-in support for OAuth 2.0 and OpenID Connect. This allows you to authenticate users via popular OAuth providers like Google, Facebook, GitHub, and more.

If your desired provider isn't directly supported, you can use the Generic OAuth Plugin for custom integrations.

This page covers signing users in with another provider. To connect each organization to its own OIDC or SAML identity provider, use SSO. To let other apps sign in with your app, use the OAuth Provider plugin.

Configuring Social Providers

To enable a social provider, you need to provide clientId and clientSecret for the provider.

Here's an example of how to configure Google as a provider:

auth.ts
import { entroAuth } from "@entro314labs/entro-auth";

export const auth = entroAuth({
  // Other configurations...
  socialProviders: {
    google: {
      clientId: "YOUR_GOOGLE_CLIENT_ID",
      clientSecret: "YOUR_GOOGLE_CLIENT_SECRET",
    },
  },
});

Usage

Sign In

To sign in with a social provider, you can use the signIn.social function with the authClient or auth.api for server-side usage.

// client-side usage
await authClient.signIn.social({
  provider: "google", // or any other provider id
})
// server-side usage
await auth.api.signInSocial({
  body: {
    provider: "google", // or any other provider id
  },
});

To link an account to a social provider, you can use the linkAccount function with the authClient or auth.api for server-side usage.

await authClient.linkSocial({
  provider: "google", // or any other provider id
})

server-side usage:

await auth.api.linkSocialAccount({
  body: {
    provider: "google", // or any other provider id
  },
  headers: await headers() // headers containing the user's session token
});

Validate OAuth User Info

Use user.validateUserInfo to reject an OAuth identity before Entro Auth creates a user, links a new account, or signs a returning user back in. The callback receives the mapped user and, in source.oauth, the provider id and raw provider profile.

It runs when an OAuth identity is first provisioned (create-user from a regular callback, ID-token sign-in, One Tap, or OAuth Proxy), when a new account is linked (link-account), and again every time an existing OAuth user signs in (sign-in). On the sign-in action the user carries the fresh provider email, so a domain check rejects a user whose provider email later moved to a disallowed domain. It works in stateless setups because it runs at the same points regardless of the database.

auth.ts
import { entroAuth } from "@entro314labs/entro-auth";

export const auth = entroAuth({
  user: {
    validateUserInfo: ({ user, source }) => {
      if (source.oauth?.providerId !== "google") return;

      if (!user.email?.endsWith("@example.com")) {
        return {
          error: "email_not_allowed",
          errorDescription: "Use your example.com email to sign in",
        };
      }
    },
  },
  socialProviders: {
    google: {
      clientId: process.env.GOOGLE_CLIENT_ID!,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
    },
  },
});

Get Access Token

Use getAccessToken to retrieve the access token for a linked account. Every token or provider-profile request must select the account explicitly: pass the Entro Auth account record's id as accountId, or pass useAccountCookie: true to select the account from its signed cookie. A providerId is never an account selector, and a request without either supported selector is invalid.

The account record ID is available from listAccounts. If its access token is expired, Entro Auth refreshes it before returning it.

const { data: accounts, error } = await authClient.listAccounts();

if (error) {
  throw new Error(error.message);
}

const account = accounts?.find((account) => account.providerId === "google");

if (!account) {
  throw new Error("Google account is not linked");
}

const { accessToken } = await authClient.getAccessToken({
  accountId: account.id,
})

When account.storeAccountCookie is enabled, select the account from the signed cookie explicitly:

const { accessToken } = await authClient.getAccessToken({
  useAccountCookie: true,
});

For server-side usage, pass the same account record ID. A trusted server call can also provide userId when it does not include session headers.

await auth.api.getAccessToken({
  body: {
    accountId: account.id,
  },
  headers: await headers(), // headers containing the user's session token
});

Refresh Access Token

Use refreshToken when you need to refresh the selected account's access token immediately. It uses the same explicit selector contract as getAccessToken.

const tokens = await authClient.refreshToken({
  accountId: account.id,
});

To use the signed account cookie instead:

await auth.api.refreshToken({
  body: {
    useAccountCookie: true,
  },
  headers: await headers(),
});

Get Account Info Provided by the provider

Use accountInfo to retrieve current profile data from the provider for a linked account. Pass the Entro Auth account record's id, not the provider's subject identifier.

The response keeps identity and profile data separate. account contains the selected Entro Auth record and its provider key, user contains mutable profile fields, and data contains the raw provider response.

const info = await authClient.accountInfo({
  query: { accountId: account.id },
});

console.log(info.data?.account.accountId);
console.log(info.data?.user.email);

When the signed account cookie should select the account:

const info = await authClient.accountInfo({
  query: { useAccountCookie: true },
});

For server-side usage:

await auth.api.accountInfo({
  query: {
    accountId: account.id,
  },
  headers: await headers(), // headers containing the user's session token
});

Requesting Additional Scopes

Sometimes your application may need additional OAuth scopes after the user has already signed up (e.g., for accessing GitHub repositories or Google Drive). Users may not want to grant extensive permissions initially, preferring to start with minimal permissions and grant additional access as needed.

You can request additional scopes by using the linkSocial method with the same provider. This will trigger a new OAuth flow that requests the additional scopes while maintaining the existing account connection. The session does not have to be fresh for this, and the flow has to come back as the account that is already linked: another one is refused with account_does_not_match.

const requestAdditionalScopes = async () => {
    await authClient.linkSocial({
        provider: "google",
        scopes: ["https://www.googleapis.com/auth/drive.file"],
    });
};

Make sure you're running Entro Auth version 1.2.7 or later. Earlier versions (like 1.2.2) may show a "Social account already linked" error when trying to link with an existing provider for additional scopes.

Customizing the Authorization URL

To forward extra query parameters to the provider's authorization endpoint, pass additionalParams when calling signIn.social or linkSocial. The values are applied after the framework has written the OAuth state, PKCE challenge, and redirect_uri; the reserved keys state, client_id, redirect_uri, response_type, code_challenge, code_challenge_method, and scope are rejected with a 400 so a caller cannot break the callback correlation.

await authClient.signIn.social({
  provider: "cognito",
  additionalParams: {
    identity_provider: "Google", // skip the Cognito hosted-UI picker
  },
});

await authClient.linkSocial({
  provider: "google",
  loginHint: "user@example.com",
  additionalParams: {
    access_type: "offline",
    prompt: "consent",
  },
});

The provider's own baked-in query parameters (for example Google's include_granted_scopes=true, Facebook's config_id, Cognito's identity_provider when set via identityProvider) are merged with call-time additionalParams; the call-time value wins on key collisions.

Passing Additional Data Through OAuth Flow

Entro Auth allows you to pass additional data through the OAuth flow without storing it in the database. This is useful for scenarios like tracking referral codes, analytics sources, or other temporary data that should be processed during authentication but not persisted.

When initiating OAuth sign-in or account linking, pass the additional data:

// Client-side: Sign in with additional data
await authClient.signIn.social({
  provider: "google",
  additionalData: {
    referralCode: "ABC123",
    source: "landing-page",
  },
});

// Client-side: Link account with additional data
await authClient.linkSocial({
  provider: "google",
  additionalData: {
    referralCode: "ABC123",
  },
});

// Server-side: Sign in with additional data
await auth.api.signInSocial({
  body: {
    provider: "google",
    additionalData: {
      referralCode: "ABC123",
      source: "admin-panel",
    },
  },
});

Accessing Additional Data in Hooks

The additional data is available in your hooks during the OAuth callback through the getOAuthState.

This usually works for OAuth callback paths such as /callback/:id.

Example using an after hook:

auth.ts
import { entroAuth } from "@entro314labs/entro-auth";
import { createAuthMiddleware, getOAuthState } from "@entro314labs/entro-auth/api";

export const auth = entroAuth({
  // Other configurations...
  hooks: {
    after: createAuthMiddleware(async (ctx) => {
      // Additional data is only available during OAuth callback
      if (ctx.path === "/callback/:id") {
        const additionalData = await getOAuthState<{
          referralCode?: string;
          source?: string;
        }>();

        if (additionalData) {
          // IMPORTANT: Validate and sanitize the data before using it
          // This data comes from the client and should not be trusted

          // Example: Validate and process referral code
          if (additionalData.referralCode) {
            const isValidFormat = /^[A-Z0-9]{6}$/.test(additionalData.referralCode);
            if (isValidFormat) {
              // Verify the referral code exists in your database
              const referral = await db.referrals.findByCode(additionalData.referralCode);
              if (referral) {
                // Safe to use the verified referral
                await db.referrals.incrementUsage(referral.id);
              }
            }
          }

          // Track analytics (low-risk usage)
          if (additionalData.source) {
            await analytics.track("oauth_signin", {
              source: additionalData.source,
              userId: ctx.context.session?.user.id,
            });
          }
        }
      }
    }),
  },
});

Example using a database hook:

auth.ts
 // You can also access additional data in database hooks
  databaseHooks: {
    user: {
      create: {
        before: async (user, ctx) => {
          if (ctx.path === "/callback/:id") {
            const additionalData = await getOAuthState<{ referredFrom?: string }>();
            if (additionalData?.referredFrom) {
              return {
                data: {
                  referredFrom: additionalData.referredFrom,
                },
              };
            }
          }
        },
      },
    },
  },

By default OAuth state includes the following data:

  • callbackURL - the callback URL for the OAuth flow
  • codeVerifier - the code verifier for the OAuth flow
  • errorURL - the error URL for the OAuth flow
  • newUserURL - the new user URL for the OAuth flow
  • link - the link for the OAuth flow (email and user id)
  • requestSignUp - whether to request sign up for the OAuth flow
  • expiresAt - the expiration time of the OAuth state
  • serverContext - server-set values that survive the redirect (see Passing Server-Trusted Data)
  • [key: string] - the additionalData you passed in. This originates from the client, so treat it as untrusted.

Passing Server-Trusted Data

additionalData is client-supplied, so it must be validated before use on the callback. When a plugin (or your own before hook) needs to carry server-derived data across the redirect, use addOAuthServerContext. It writes to a server-only slot that the client cannot populate, and the values are readable on the callback under serverContext.

auth.ts
import { entroAuth } from "@entro314labs/entro-auth";
import {
  addOAuthServerContext,
  createAuthMiddleware,
  getOAuthState,
} from "@entro314labs/entro-auth/api";

export const auth = entroAuth({
  hooks: {
    before: createAuthMiddleware(async (ctx) => {
      // Social and generic OAuth providers both sign in here.
      if (ctx.path === "/sign-in/social") {
        // Derived on the server, so it is safe to trust on the callback.
        await addOAuthServerContext({ tenantId: ctx.context.tenantId });
      }
    }),
    after: createAuthMiddleware(async (ctx) => {
      if (ctx.path === "/callback/:id") {
        const tenantId = (await getOAuthState())?.serverContext?.tenantId;
        // Safe to use without re-validation: the client could not set this.
      }
    }),
  },
});

Handling Providers Without Email

Entro Auth currently requires an email address on every user record. Most providers return one with the email scope, but several can legitimately omit it. When that happens the OAuth flow fails with error=email_not_found (or error=email_is_missing for the Generic OAuth plugin).

The table below summarises, for each affected provider, when email may be absent, which stable identifier you can use as a fallback in mapProfileToUser, and how much to trust the provider's email_verified signal.

ProviderWhen email may be absentStable fallback IDemail_verified trust
AppleEmail may be empty for Work & School accounts. It is included in subsequent identity tokensprofile.sub (stable per Apple Team)Can be false for Work & School accounts
DiscordPhone-only accounts; email scope not grantedprofile.id (snowflake)Reliable (dedicated verified field)
FacebookNo valid email on file, even with the email permission grantedprofile.id (app-scoped)Unknown: Graph API exposes no per-email verification flag
GitHubUser has set email to private; GitHub App lacks the "Email addresses" permissionprofile.id (numeric)Reliable
Kakaoaccount_email is not requested, not enabled for the app, or not granted by the userprofile.id (numeric)Reliable
LinkedInNo confirmed email on the member; email scope not grantedprofile.sub (pairwise per app)Reliable when present
Microsoft Entra IDManaged users without a mail attribute, unless email is configured as an optional claimprofile.oid (stable within profile.tid)Untrustworthy: Microsoft explicitly warns never to use for authorization
RobloxThe default Roblox profile flow does not return an email; Entro Auth creates a non-routable placeholder from profile.subprofile.sub (Roblox user ID)Unknown for the default profile flow

Create a placeholder email with mapProfileToUser

Fall back to the provider's stable ID when the email field is null or absent:

auth.ts
import { entroAuth } from "@entro314labs/entro-auth";

export const auth = entroAuth({
  socialProviders: {
    discord: {
      clientId: process.env.DISCORD_CLIENT_ID!,
      clientSecret: process.env.DISCORD_CLIENT_SECRET!,
      mapProfileToUser: (profile) => ({
        email: profile.email ?? `${profile.id}@discord.placeholder.invalid`,
      }),
    },
    apple: {
      clientId: process.env.APPLE_CLIENT_ID!,
      clientSecret: process.env.APPLE_CLIENT_SECRET!,
      mapProfileToUser: (profile) => ({
        email: profile.email ?? `${profile.sub}@apple.placeholder.invalid`,
      }),
    },
    microsoft: {
      clientId: process.env.MICROSOFT_CLIENT_ID!,
      clientSecret: process.env.MICROSOFT_CLIENT_SECRET!,
      mapProfileToUser: (profile) => ({
        email: profile.email ?? `${profile.oid}@entra.placeholder.invalid`,
      }),
    },
  },
});

Placeholder emails are not contact addresses. Plugins that send mail (password reset, magic link, email verification, organization invites) cannot deliver to them. Use a domain you control or the reserved .invalid domain so no real inbox is ever addressed by mistake.

Provider-specific notes

  • Apple: returns the user’s name only on first authorization. Email is included in subsequent identity tokens, although Work & School accounts may have an empty email. email_verified and is_private_email can be booleans or the strings "true" and "false". Supply a fallback email through mapProfileToUser when needed.
  • GitHub: the user:email scope is requested by default. Private emails still return null on /user; the primary verified address is available at /user/emails.
  • Microsoft Entra ID: because email is tenant-mutable and never verified, use profile.oid (immutable, stable within the tenant) as the identity anchor; treat email as a profile attribute only. Microsoft's claims validation guidance explicitly warns never to use email, preferred_username, or unique_name for authorization decisions.
  • Facebook: without a per-email verification flag, treat every Facebook email as unverified unless you run your own verification challenge.

Entro Auth recognizes a returning OAuth account by its stable (providerId, accountId) key, but the linked Entro Auth user still requires an email address. Support for users without an email is tracked in #9124.

Provider Options

clientId

The OAuth 2.0 Client ID issued by the provider.

For providers that verify ID tokens by audience (Google, Apple, Microsoft Entra, Facebook, Cognito), you can pass an array to accept tokens issued for any of the configured clients. The first entry is used when Entro Auth drives the authorization code flow; all entries are accepted when verifying an ID token's aud claim. This enables cross-platform sign-in (Web, iOS, Android) with a single backend configuration, where each platform's native SDK issues tokens under its own Client ID.

auth.ts
import { entroAuth } from "@entro314labs/entro-auth";

export const auth = entroAuth({
  // Other configurations...
  socialProviders: {
    google: {
      clientId: [
        process.env.GOOGLE_WEB_CLIENT_ID as string,
        process.env.GOOGLE_IOS_CLIENT_ID as string,
        process.env.GOOGLE_ANDROID_CLIENT_ID as string,
      ],
      clientSecret: process.env.GOOGLE_CLIENT_SECRET as string,
    },
  },
});

All Client IDs must live in the same provider project so consent is shared. For providers that don't verify ID tokens by audience, only a single string is accepted.

scope

The scope of the access request. For example, email or profile.

auth.ts
import { entroAuth } from "@entro314labs/entro-auth";

export const auth = entroAuth({
  // Other configurations...
  socialProviders: {
    google: {
      clientId: "YOUR_GOOGLE_CLIENT_ID",
      clientSecret: "YOUR_GOOGLE_CLIENT_SECRET",
      scope: ["email", "profile"],
    },
  },
});

redirectURI

Custom redirect URI for the provider. By default, it uses /api/auth/callback/${providerName}

auth.ts
import { entroAuth } from "@entro314labs/entro-auth";

export const auth = entroAuth({
  // Other configurations...
  socialProviders: {
    google: {
      clientId: "YOUR_GOOGLE_CLIENT_ID",
      clientSecret: "YOUR_GOOGLE_CLIENT_SECRET",
      redirectURI: "https://your-app.com/auth/callback",
    },
  },
});

authorizationEndpoint, tokenEndpoint, userInfoEndpoint, jwksEndpoint

Point a built-in provider at a different server, such as a local OAuth emulator, a mock server, or a sandbox environment. Without these options, each provider uses its own production endpoints.

auth.ts
import { entroAuth } from "@entro314labs/entro-auth";

export const auth = entroAuth({
  // Other configurations...
  socialProviders: {
    google: {
      clientId: "YOUR_GOOGLE_CLIENT_ID",
      clientSecret: "YOUR_GOOGLE_CLIENT_SECRET",
      authorizationEndpoint: "http://localhost:3000/o/oauth2/v2/auth",
      tokenEndpoint: "http://localhost:3000/oauth2/token",
      userInfoEndpoint: "http://localhost:3000/oauth2/v2/userinfo",
      jwksEndpoint: "http://localhost:3000/oauth2/v3/certs",
    },
  },
});

All four options are optional:

  • authorizationEndpoint: The URL that starts sign-in.
  • tokenEndpoint: The URL for the authorization code exchange and for refresh requests. When the provider signs a client assertion (private_key_jwt), its audience is this URL.
  • userInfoEndpoint: The URL that returns the user's profile.
  • jwksEndpoint: The URL of the key set that verifies ID tokens.

Entro Auth sends your client secret and the authorization code to tokenEndpoint, and the user's access token to userInfoEndpoint. Facebook's debug_token check receives the access token too. Point them only at servers you run or trust, and never build them from user input.

A provider ignores an option when it has no matching step. Google, Apple, and Microsoft Entra ID read the profile from the ID token, so they ignore userInfoEndpoint. Only Apple, Cognito, Facebook, Google, Kakao, and Microsoft Entra ID verify ID tokens with a key set, so only they read jwksEndpoint.

If an endpoint URL already has a query string, Entro Auth keeps it and adds its own parameters after it.

ID token issuer

jwksEndpoint changes where the signing keys come from. It does not change who may be the issuer. Entro Auth still requires the provider's own issuer and your client ID in the ID token. An emulator must therefore mint ID tokens with the provider's issuer, for example https://accounts.google.com for Google.

Microsoft Entra ID builds its issuer from authority and tenantId. To accept ID tokens from an emulator that uses its own issuer, set authority to the emulator instead of using jwksEndpoint alone.

Provider-specific behavior

  • GitHub: When the profile has no email, Entro Auth requests the email list from the /emails path next to the user endpoint. The lookup runs only when your userInfoEndpoint path ends with /user, such as https://ghe.example.com/api/v3/user. For other paths, the email comes from the profile response only.
  • Facebook: Before it reads the profile, Entro Auth checks the access token with the debug_token endpoint. When you set userInfoEndpoint, this check uses the debug_token path next to it, for example https://emulator.example.com/graph/debug_token for https://emulator.example.com/graph/me.
  • Microsoft Entra ID: The profile photo comes from Microsoft Graph and does not follow userInfoEndpoint. Set disableProfilePhoto: true when you test without Microsoft Graph.
  • Cloudflare: userInfoEndpoint must return Cloudflare's /user response shape, an object with success, errors, and result, not a flat OpenID Connect profile.
  • LINE: LINE verifies ID tokens with its own verify endpoint, not a key set, so jwksEndpoint has no effect.
  • WeChat: WeChat refreshes tokens at a different URL than the code exchange. Set refreshTokenEndpoint for the refresh request, and tokenEndpoint for the code exchange.
auth.ts
import { entroAuth } from "@entro314labs/entro-auth";

export const auth = entroAuth({
  // Other configurations...
  socialProviders: {
    wechat: {
      clientId: "YOUR_WECHAT_APP_ID",
      clientSecret: "YOUR_WECHAT_APP_SECRET",
      tokenEndpoint: "http://localhost:3000/sns/oauth2/access_token",
      refreshTokenEndpoint: "http://localhost:3000/sns/oauth2/refresh_token",
      userInfoEndpoint: "http://localhost:3000/sns/userinfo",
    },
  },
});

disableSignUp

Disables sign-up for new users.

disableIdTokenSignIn

Disables the use of the ID token for sign-in. By default, it's enabled for some providers like Google and Apple.

verifyIdToken

A custom function to verify the ID token. Receives the token, an optional nonce, and the request endpoint context so you can branch on headers or other request data.

Providing verifyIdToken replaces the provider's built-in verification (signature, issuer, audience, and the exp, nbf, and iat time checks, which allow 30 seconds of clock skew). Your callback must perform those checks itself, including any clock tolerance. Client-supplied headers such as x-platform are attacker-controlled — use them only to select which audience (or other claim) to verify against, not as proof of identity on their own.

auth.ts
import { entroAuth } from "@entro314labs/entro-auth";
import { createRemoteJWKSet, jwtVerify } from "jose";

const appleJwks = createRemoteJWKSet(
  new URL("https://appleid.apple.com/auth/keys"),
);

export const auth = entroAuth({
  socialProviders: {
    apple: {
      clientId: "YOUR_APPLE_CLIENT_ID",
      clientSecret: "YOUR_APPLE_CLIENT_SECRET",
      verifyIdToken: async (token, nonce, ctx) => {
        // Select audience from the request, then cryptographically verify.
        const audience =
          ctx?.headers?.get("x-platform") === "ios"
            ? process.env.APPLE_APP_BUNDLE_IDENTIFIER!
            : process.env.APPLE_CLIENT_ID!;
        try {
          const { payload } = await jwtVerify(token, appleJwks, {
            issuer: "https://appleid.apple.com",
            audience,
            maxTokenAge: "1h",
            clockTolerance: 30,
          });
          if (nonce && payload.nonce !== nonce) {
            return false;
          }
          return true;
        } catch {
          return false;
        }
      },
    },
  },
});

requireIssuedIdTokenNonce

Binds each ID token a client submits to one request. When enabled, signIn.social and linkSocial with an idToken require a nonce from POST /id-token/nonce. Each nonce works once and expires after five minutes. The token's nonce claim must match it. Without it, the server has no record of the nonces a client uses, so it cannot tell a fresh token from a reused one.

Enable it only when every client that submits ID tokens for this provider can pass a nonce to the provider's SDK. Clients that send no nonce, or one the server did not issue, get 400 INVALID_ID_TOKEN_NONCE.

auth.ts
export const auth = entroAuth({
  socialProviders: {
    google: {
      clientId: process.env.GOOGLE_CLIENT_ID!,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
      requireIssuedIdTokenNonce: true,
    },
  },
});

Fetch a nonce before you start the provider's sign-in, pass it to the provider's SDK, then send it with the ID token:

client.ts
const { data } = await authClient.idToken.nonce({ provider: "google" });

// Pass data.nonce to the provider's SDK, e.g. Google's `nonce` option,
// then submit the ID token it returns.
await authClient.signIn.social({
  provider: "google",
  idToken: { token: idTokenFromProvider, nonce: data.nonce },
});
  • Apple: Apple recommends passing the SHA-256 hex digest of the nonce to Apple, and sending the raw nonce to Entro Auth. Built-in verification accepts either the raw value or its digest in the claim. A custom verifyIdToken for Apple must do the same comparison itself.
  • Google One Tap: always requires a nonce and does not read this option. See Nonce.
  • Facebook: only Limited Login ID tokens carry a nonce. Opaque Graph access tokens are rejected when a nonce is expected.
  • Custom verifyIdToken: Entro Auth consumes the issued nonce and passes it to your function, so your function must still compare it to the token's nonce claim and reject tokens that cannot carry one.

overrideUserInfoOnSignIn

A boolean value that determines whether to override the user information in the database when signing in. By default, it is set to false, meaning that the user information will not be overridden during sign-in. If you want to update the user information every time they sign in, set this to true.

requireEmailVerification

Require this provider's email to be verified before a session is created. Defaults to false.

When the provider reports the email as unverified, Entro Auth still creates or links the user and account, but it does not issue a session. The OAuth callback redirects with ?error=email_not_verified, and ID token sign-in returns a 403 with the EMAIL_NOT_VERIFIED error code. A verification email is (re)sent according to your emailVerification settings: sendOnSignUp covers new users and sendOnSignIn covers returning users. Configure emailVerification.sendVerificationEmail and keep sendOnSignUp enabled so blocked users always receive a link to verify.

The gate checks the local user's verification state rather than the provider's claim on each request. A user already verified through another method (such as email and password) keeps access even if the provider later reports the email as unverified.

auth.ts
import { entroAuth } from "@entro314labs/entro-auth";

export const auth = entroAuth({
  socialProviders: {
    google: {
      clientId: process.env.GOOGLE_CLIENT_ID!,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
      requireEmailVerification: true,
    },
  },
});

This is opt-in per provider and is independent of emailAndPassword.requireEmailVerification: enabling email and password verification does not gate social sign-in.

Only enable this for providers that report a trustworthy email_verified signal. Several providers always report the email as unverified (or never return one), so enabling it there blocks every sign-in. See Handling Providers Without Email.

mapProfileToUser

Use mapProfileToUser to change the default user mapping or populate additional user fields from the provider profile.

Entro Auth treats the function's return value as provider input, even though the function runs on your server. It applies the input rules from user.additionalFields during OAuth sign-up, sign-in profile override, and account-link profile sync. Mapped fields that allow input are parsed and stored, while mapped values for fields marked input: false are ignored.

Profile mapping cannot redefine the provider account identity. Built-in providers derive identity from their documented immutable profile field. Generic OAuth providers use accountSubject when the default sub or id field is not the correct identifier.

auth.ts
import { entroAuth } from "@entro314labs/entro-auth";

export const auth = entroAuth({
  // Other configurations...
  socialProviders: {
    google: {
      clientId: "YOUR_GOOGLE_CLIENT_ID",
      clientSecret: "YOUR_GOOGLE_CLIENT_SECRET",
      mapProfileToUser: (profile) => {
        return {
          firstName: profile.given_name,
          lastName: profile.family_name,
        };
      },
    },
  },
});

Declare mapped fields in the user.additionalFields option and allow those fields as input. The same rule applies to stateless auth setups.

Server-Owned Fields and Authorization Claims

Keep security-sensitive fields such as roles, bans, internal flags, and organization membership at input: false. Do not enable input only so mapProfileToUser can persist a provider claim, because the same setting also lets generic sign-up and user-update requests supply that field.

input and returned control separate directions. For example, { input: false, returned: true } defines a readable server-owned field. API input and mapProfileToUser cannot supply it, but Entro Auth includes its stored value in responses.

The Provider's Stable ID

Do not carry a provider's own id for a person (a GitHub user id, a Google sub) in a user field. A field mapProfileToUser can fill is one /update-user can rewrite, and one marked input: false is never filled by the mapper: the value is absent, with no error. The id is already stored where a request cannot change it, as the accountId of the person's account for that providerId. Read it on the server:

const accounts = await auth.api.listUserAccounts({ headers });
const github = accounts.find((account) => account.providerId === "github");
const githubId = github?.accountId;

An allow-list by provider id ("only this GitHub account may enter") compares against that value. Without a database the account travels in a signed cookie and listUserAccounts reads it from there.

If a provider claim controls who may sign in, enforce the policy before Entro Auth completes OAuth sign-in. Do not defer the check until after sign-in, because Entro Auth may already have issued a valid session. Prefer a provider-specific option when one exists, such as the Google provider's hd option for a Google Workspace domain. For flows that invoke getUserInfo, a custom implementation can verify the provider response and return null when the policy fails. Configure equivalent enforcement for separate sign-in paths that do not invoke getUserInfo.

If you also need to store the verified claim, keep the field at input: false and write it with your application's database layer. Use defaultValue only for a static value that applies to every user created through that auth configuration, not for a value derived from a provider profile.

getAccountFields

Use getAccountFields to store your own values on the provider account, such as the email address the provider reports or the tenant a user signed in from. Add a column for each value to account.additionalFields, then return the values from the hook. Run npx @entro314labs/entro-auth-cli@latest migrate after you add a field.

auth.ts
import { entroAuth } from "@entro314labs/entro-auth";

export const auth = entroAuth({
  // Other configurations...
  account: {
    additionalFields: {
      providerEmail: {
        type: "string",
        required: false,
      },
    },
  },
  socialProviders: {
    google: {
      clientId: "YOUR_GOOGLE_CLIENT_ID",
      clientSecret: "YOUR_GOOGLE_CLIENT_SECRET",
      getAccountFields: async (tokens, userInfo) => {
        return {
          providerEmail: userInfo.email,
        };
      },
    },
  },
});

The hook receives the provider's tokens and the normalized user info. It runs only when you set it, after Entro Auth verifies the provider response, so a provider without getAccountFields behaves as before.

Entro Auth writes the returned values when it creates the account and when it updates it:

  • A new user signs in, or an existing user signs in with a provider for the first time.
  • A signed-in user links the provider.
  • A user who is already linked signs in again or links again. On sign-in, Entro Auth updates the values only while updateAccountOnSignIn is not false.

This covers the redirect flow and ID token sign-in and linking. For an ID token, the tokens argument holds only what the client sent: the idToken, plus the accessToken and refreshToken when the client includes them. Sign-in through One Tap and the OAuth Proxy plugin does not call the hook.

Entro Auth ignores these returned values:

  • Keys that are not declared in account.additionalFields or by a plugin.
  • Fields marked input: false.
  • Values that are undefined. A stored value stays as it is.
  • Entro Auth's own account columns: id, userId, providerId, accountId, accessToken, refreshToken, idToken, accessTokenExpiresAt, refreshTokenExpiresAt, scope, password, createdAt, and updatedAt. A returned value can never rebind an account or replace its tokens.

Return null for the whole result to store nothing. A null value for a key is stored as null and replaces the stored value.

Values pass through the field's validator.input and transform.input. A value that fails validation stops the sign-in or link with a validation error, even when updateAccountOnSignIn is false and the value is not stored. In the redirect flow, the user lands on your error URL with error=VALIDATION_ERROR.

Entro Auth treats the returned values as provider input, like the values from mapProfileToUser. Keep security-sensitive fields, such as roles or internal flags, at input: false so that a provider claim cannot set them. Do not copy a provider claim you have not verified into a field your application trusts for authorization. See server-owned fields and authorization claims.

refreshAccessToken

A custom function to refresh the token. This feature is only supported for built-in social providers (Google, Facebook, GitHub, etc.) and is not currently supported for custom OAuth providers configured through the Generic OAuth Plugin. For built-in providers, you can provide a custom function to refresh the token if needed.

auth.ts
import { entroAuth } from "@entro314labs/entro-auth";

export const auth = entroAuth({
  // Other configurations...
  socialProviders: {
    google: {
      clientId: "YOUR_GOOGLE_CLIENT_ID",
      clientSecret: "YOUR_GOOGLE_CLIENT_SECRET",
      refreshAccessToken: async (token) => {
        return {
          accessToken: "new-access-token",
          refreshToken: "new-refresh-token",
        };
      },
    },
  },
});

clientKey

The client key of your application. This is used by TikTok Social Provider instead of clientId.

auth.ts
import { entroAuth } from "@entro314labs/entro-auth";

export const auth = entroAuth({
  // Other configurations...
  socialProviders: {
    tiktok: {
      clientKey: "YOUR_TIKTOK_CLIENT_KEY",
      clientSecret: "YOUR_TIKTOK_CLIENT_SECRET",
    },
  },
});

getUserInfo

A custom function to get user info from the provider. This allows you to override the default user info retrieval process.

auth.ts
import { entroAuth } from "@entro314labs/entro-auth";

export const auth = entroAuth({
  // Other configurations...
  socialProviders: {
    google: {
      clientId: "YOUR_GOOGLE_CLIENT_ID",
      clientSecret: "YOUR_GOOGLE_CLIENT_SECRET",
      getUserInfo: async (token) => {
        // Custom implementation to get user info
        const response = await fetch("https://www.googleapis.com/oauth2/v2/userinfo", {
          headers: {
            Authorization: `Bearer ${token.accessToken}`,
          },
        });
        const profile = await response.json();
        return {
          user: {
            name: profile.name,
            email: profile.email,
            image: profile.picture,
            emailVerified: profile.verified_email,
          },
          data: profile,
        };
      },
    },
  },
});

disableImplicitSignUp

Disables implicit sign up for new users. When set to true for the provider, sign-in needs to be called with requestSignUp as true to create new users.

auth.ts
import { entroAuth } from "@entro314labs/entro-auth";

export const auth = entroAuth({
  // Other configurations...
  socialProviders: {
    google: {
      clientId: "YOUR_GOOGLE_CLIENT_ID",
      clientSecret: "YOUR_GOOGLE_CLIENT_SECRET",
      disableImplicitSignUp: true,
    },
  },
});

prompt

The prompt to use for the authorization code request. This controls the authentication flow behavior.

auth.ts
import { entroAuth } from "@entro314labs/entro-auth";

export const auth = entroAuth({
  // Other configurations...
  socialProviders: {
    google: {
      clientId: "YOUR_GOOGLE_CLIENT_ID",
      clientSecret: "YOUR_GOOGLE_CLIENT_SECRET",
      prompt: "select_account", // or "consent", "login", "none", "select_account+consent"
    },
  },
});

responseMode

The response mode to use for the authorization code request. This determines how the authorization response is returned.

auth.ts
import { entroAuth } from "@entro314labs/entro-auth";

export const auth = entroAuth({
  // Other configurations...
  socialProviders: {
    google: {
      clientId: "YOUR_GOOGLE_CLIENT_ID",
      clientSecret: "YOUR_GOOGLE_CLIENT_SECRET",
      responseMode: "query", // or "form_post"
    },
  },
});

disableDefaultScope

Removes the default scopes of the provider. By default, providers include certain scopes like email and profile. Set this to true to remove these default scopes and use only the scopes you specify.

auth.ts
import { entroAuth } from "@entro314labs/entro-auth";

export const auth = entroAuth({
  // Other configurations...
  socialProviders: {
    google: {
      clientId: "YOUR_GOOGLE_CLIENT_ID",
      clientSecret: "YOUR_GOOGLE_CLIENT_SECRET",
      disableDefaultScope: true,
      scope: ["https://www.googleapis.com/auth/userinfo.email"], // Only this scope will be used
    },
  },
});

Other Provider Configurations

Each provider may have additional options, check the specific provider documentation for more details.

On this page