# Set up sign-in providers

Enable six social OAuth2 providers, email and password login, and 6-digit One-Time Password (OTP) flows using environment variables or Go configuration without manual PocketBase admin setup.

![Google, Microsoft, GitHub, Apple, Hugging Face, ChatGPT and email sign-in](assets/providers.svg)

> [!IMPORTANT]
> Every provider sends returning visitors to `https://your_app.example/api/oauth2-redirect`. Register that URL in each provider app alongside `http://127.0.0.1:8090/api/oauth2-redirect` for local development.

## Social providers

Create an OAuth client with each provider you support and export its environment variables before starting PocketBase. Any provider without credentials stays hidden from [AuthCard](ui.md#authcard).

| Provider     | Environment variables                                       | Where to create the client                                                                                                                                                 |
| ------------ | ----------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Google       | `GOOGLE_CLIENT_ID`, `GOOGLE_CLIENT_SECRET`                  | [Google Auth Platform](https://developers.google.com/identity/protocols/oauth2/web-server) web application client                                                          |
| Microsoft    | `MICROSOFT_CLIENT_ID`, `MICROSOFT_CLIENT_SECRET`            | [Microsoft Entra app registrations](https://learn.microsoft.com/en-us/entra/identity-platform/quickstart-register-app) web platform                                        |
| GitHub       | `GITHUB_CLIENT_ID`, `GITHUB_CLIENT_SECRET`                  | [GitHub App](https://docs.github.com/en/apps/creating-github-apps/about-creating-github-apps/about-creating-github-apps) with `Email addresses: Read-only` or an OAuth App |
| Apple        | `APPLE_CLIENT_ID` plus a `.p8` key ([below](#apple-p8-key)) | [Apple Developer](https://developer.apple.com/documentation/signinwithapple/configuring-your-environment-for-sign-in-with-apple) App ID, Services ID, and key              |
| Hugging Face | `HF_CLIENT_ID`, `HF_CLIENT_SECRET`                          | [Hugging Face Connected Applications](https://huggingface.co/docs/hub/oauth) with `openid`, `profile`, and `email` scopes                                                  |
| ChatGPT      | `CHATGPT_CLIENT_ID`, `CHATGPT_CLIENT_SECRET`                | OpenAI OAuth client with your redirect URL                                                                                                                                 |

Hugging Face also reads `HUGGINGFACE_CLIENT_ID` and `HUGGINGFACE_CLIENT_SECRET`, and ChatGPT also reads `OPENAI_OAUTH_CLIENT_ID` and `OPENAI_OAUTH_CLIENT_SECRET`. Each provider expects these extra settings:

- **Microsoft**: Add the optional ID token claims `email` and `xms_edov` under **Token configuration** so pbauth rejects unverified work emails and blocks [nOAuth pre-hijacking](linking.md#why-email-matching-is-blocked)
- **GitHub**: Grant email read permission so pbauth reads verified primary addresses from `/user/emails`
- **Hugging Face and ChatGPT**: Leave OpenID Connect (OIDC) endpoints unconfigured because pbauth wires them into PocketBase’s `oidc` and `oidc2` slots and checks ID tokens against published keys

### Apple .p8 key

Sign in with Apple uses a JSON Web Token (JWT) client secret that expires every 180 days. Supply your `.p8` private key so pbauth signs a 150-day secret at startup and rotates it weekly via `AppleRefreshCron`:

| Variable            | Value                                                                            |
| ------------------- | -------------------------------------------------------------------------------- |
| `APPLE_CLIENT_ID`   | Services ID such as `com.example.web`                                            |
| `APPLE_TEAM_ID`     | 10-character Apple Team ID                                                       |
| `APPLE_KEY_ID`      | 10-character Sign in with Apple Key ID                                           |
| `APPLE_PRIVATE_KEY` | Contents of your `.p8` file (escaped `\n` newlines are normalized automatically) |

A fixed `APPLE_CLIENT_SECRET` still works if you prefer to rotate secrets outside PocketBase.

## Email and OTP

Call `pbauth.EmailAuthFromEnv()` for `Config.EmailAuth` to configure password sign-in, 6-digit email OTP verification, and password reset from environment variables:

| Variable                            | Default | Effect                                            |
| ----------------------------------- | ------- | ------------------------------------------------- |
| `PBAUTH_EMAIL_AUTH`                 | `false` | Enables email and password sign-in                |
| `PBAUTH_EMAIL_SIGNUP`               | `false` | Allows new account registration by email          |
| `PBAUTH_MIN_PASSWORD_LENGTH`        | `8`     | Minimum accepted password length                  |
| `PBAUTH_DISABLE_EMAIL_VERIFICATION` | `false` | Lets unverified accounts sign in                  |
| `PBAUTH_DISABLE_PASSWORD_RESET`     | `false` | Disables password reset flows                     |
| `PBAUTH_ALLOW_EMAIL_CHANGE`         | `false` | Lets signed-in accounts change their email        |
| `PBAUTH_VERIFICATION_MODE`          | `"otp"` | Selects `"otp"` 6-digit codes or `"link"` emails  |
| `PBAUTH_PASSWORD_RESET_MODE`        | `"otp"` | Selects `"otp"` 6-digit codes or `"link"` emails  |
| `PBAUTH_OTP_LOGIN`                  | `false` | Turns on passwordless email OTP sign-in           |
| `PBAUTH_OTP_LENGTH`                 | `6`     | Numeric code length, clamped between `6` and `10` |
| `PBAUTH_OTP_DURATION_SECONDS`       | `300`   | Code expiration lifetime in seconds               |

Signup verification and password reset default to `"otp"` mode with strict purpose scoping so verification codes can’t replay on passwordless or reset routes:

| Flow               | Request and confirm endpoints                              | Security behavior                                                  |
| ------------------ | ---------------------------------------------------------- | ------------------------------------------------------------------ |
| Email verification | `POST /api/auth/otp/verify/request`, `/otp/verify/confirm` | Checks the signup password alongside the OTP to stop pre-hijacking |
| Password reset     | `POST /api/auth/otp/reset/request`, `/otp/reset/confirm`   | Sets the new password inside the same confirmation request         |
| Passwordless login | PocketBase `requestOTP` and `authWithOTP`                  | Enabled when `EnablePasswordlessOTP` or `PBAUTH_OTP_LOGIN` is on   |

> [!TIP]
> Built-in OTP and link emails localize across `en`, `tr`, `ar` with Right-to-Left (RTL) layout, `es`, `fr`, and `de` from `Accept-Language` or `LocaleFromRequest`. Override any message template with `EmailAuthConfig.RenderEmail`, and see [verify and reset with email OTP](ui.md#verify-and-reset-with-email-otp) for the React UI.

Set these outgoing mail server (SMTP) variables to deliver verification and reset messages:

| Variable     | Effect                                                                                                |
| ------------ | ----------------------------------------------------------------------------------------------------- |
| `PUBLIC_URL` | Base URL used inside link-mode confirmation emails                                                    |
| `MAIL_FROM`  | Sender header such as `Acme <hi@acme.dev>`                                                            |
| `SMTP_URL`   | `smtp://user:pass@host` for STARTTLS on port `587`, or `smtps://user:pass@host` for TLS on port `465` |

pbauth enforces native PocketBase rate limits of 10 password login attempts per minute and 5 verification or reset emails per minute. When `Config.AllowEmail` is set, it also gates email signup, verification, password reset, and email changes.

## How same-tab sign-in works

Social sign-in runs inside the visitor’s starting tab with Proof Key for Code Exchange (PKCE) `S256` so popup blockers and embedded browsers can’t interrupt login.

![Same-tab sign-in from provider redirect to session exchange](assets/auth-flow.svg)

1. **Start**: `GET /api/auth/oauth/{provider}/start` verifies that `return_to` stays on your origin (over 3072 bytes it keeps only the path, or `/` when the path alone is longer), creates a PKCE `S256` challenge with a 600s state, and binds it to an `HttpOnly` cookie scoped to `/api/oauth2-redirect`.
2. **Callback**: The provider redirects back to `/api/oauth2-redirect`, where pbauth verifies the cookie and redirects to `return_to` with a one-time ticket in the URL fragment (or `?auth_error=` on failure). PocketBase’s activity log skips successful start and callback requests, since their URLs carry the `login_hint` email and the provider’s code.
3. **Exchange**: The React client posts the fragment ticket to `/api/auth/oauth/exchange` within 60s to receive a PocketBase session.

Apple posts its callback as an HTML form, so pbauth converts that POST into a `303` redirect to `/api/oauth2-redirect` before running the cookie check. PocketBase’s legacy popup mode keeps working when a callback state lacks the `pbauth_` prefix (`flow: "popup"`).

## Provider names in the API

PocketBase stores Hugging Face in `oidc` and ChatGPT in `oidc2`, while pbauth exposes canonical keys in HTTP responses and accepts either form in `Config`:

| Provider                         | Key in pbauth | Name in PocketBase |
| -------------------------------- | ------------- | ------------------ |
| Hugging Face                     | `huggingface` | `oidc`             |
| ChatGPT                          | `chatgpt`     | `oidc2`            |
| Google, Microsoft, GitHub, Apple | Same in both  | Same in both       |

Call `pbauth.CanonicalProviderKey` and `pbauth.PocketBaseProviderName` when converting between the two forms in Go.

## Configure the Go plugin

Every field on `pbauth.Config` is optional when configuring via code or mixing hooks with environment defaults:

| Field                             | Default                                     | Purpose                                                                                                      |
| --------------------------------- | ------------------------------------------- | ------------------------------------------------------------------------------------------------------------ |
| `Collection`                      | `"users"`                                   | PocketBase auth collection managed by pbauth                                                                 |
| `AllowedProviders`                | all 6 providers                             | Restricts accepted social providers for the collection                                                       |
| `Providers`                       | loaded from env                             | Programmatic provider overrides (custom scopes via `provider.Scopes()` stay intact)                          |
| `MaxPerProvider`                  | unlimited                                   | Caps linked identities per provider (`0` blocks linking that provider)                                       |
| `EmailAuth`                       | off                                         | Email, password, OTP, and template configuration (`EmailAuthFromEnv()`)                                      |
| `SessionDuration`                 | collection default                          | Custom authentication token lifetime                                                                         |
| `RoutePrefix`                     | `"/api/auth"`                               | Base path prefix for pbauth API routes                                                                       |
| `ExposeMethodsRoute`              | `false`                                     | Serves `GET your_route_prefix/methods` to signed-out visitors                                                |
| `AllowEmail`                      | none                                        | Predicate deciding which email addresses can sign in or register                                             |
| `IsAuthorizedUser`                | none                                        | Runs on every session, sign-in, and linked-account route                                                     |
| `AllowExistingUnlinkedEmailMatch` | `false`                                     | Lets a first OAuth login claim an existing unlinked record matching the email                                |
| `AllowUnlinkLastWhenPasswordSet`  | `false`                                     | Lets accounts with a verified password remove their final social login                                       |
| `OnUserSync`                      | none                                        | Syncs provider profile data onto the record after OAuth login                                                |
| `OnBeforeOAuthCreate`             | none                                        | Returns `e.CreateData` fields for brand-new OAuth signups after `AllowEmail` passes                          |
| `OnAccountProof`                  | none                                        | Adds custom non-reserved JWT claims and meta fields during [proof creation](linking.md#link-another-account) |
| `OnAccountConnect`                | none                                        | Runs inside the connect database transaction with verified claims and optional JSON `extra`                  |
| `OnOAuthSuccess`                  | none                                        | Post-login hook running after `OnUserSync` completes                                                         |
| `OnMerge`                         | none                                        | Combines two user records in [account merge flows](linking.md#combine-accounts-owned-by-someone-else)        |
| `ProofHeaders`                    | `X-Account-Proof`, `X-PBAuth-Account-Proof` | Request headers switching an OAuth login into account-proof mode                                             |
| `ProofSecretSuffix`               | `"pbauth-account-proof"`                    | Suffix appended to token keys when signing linking proofs                                                    |
| `ProofTTL`                        | `300s`                                      | Lifetime of an ownership-proof JWT                                                                           |
| `DisableCOOPMiddleware`           | `false`                                     | Skips setting `Cross-Origin-Opener-Policy` headers                                                           |
| `AppleRefreshCron`                | `"0 3 * * 0"`                               | Cron schedule for rotating Apple `.p8` client secrets                                                        |

Reserved proof claim keys (`provider`, `identity`, `email`, `owner`, `exp`, `iat`, `nbf`, `sub`) and reserved metadata keys (`proof`, `owner`, `email`, `provider`) are protected against overrides in `OnAccountProof`.
