User Authentication
User authentication provides login, registration, and identity management for your end users. Foir supports password-based login, one-time passwords (OTP), and OAuth/OIDC providers.
In the SDK:
@foir/sdk/authmakes every request on this page, one function each, and keeps the session each one mints or ends: it stores the token, schedules its refresh and survives a redirect, wired into@foir/sdk/reactand@foir/sdk/next. Your manifest publishes the same operations as theauthnamespace, so they are typed operations on the data client too. Authenticate with@foir/sdk/auth, then hand the access token to@foir/sdk/data; see Choosing an API Style.
Overview
Authentication Methods
| Method | Description | Use Case |
|---|---|---|
| Password | Email + password | Traditional login |
| OTP | One-time password sent via email | Passwordless login |
| OAuth/OIDC | External identity providers (Google, Auth0, etc.) | Social login, SSO |
All methods return an access token and a refresh token on success. The access token is sent in the Authorization header to identify the user.
For hosted sign-in, where Foir hosts the sign-in page so you don’t build one and your app gets back the same EdDSA user tokens, see the hosted sign-in guide.
Tokens
- Access token: a short-lived (15-minute) EdDSA JWT sent as
Authorization: Bearer …. To verify it server-side, fetch the public keys fromhttps://api.foir.dev/.well-known/jwks.jsonand check that its issuer is theissuerthe discovery document names:https://api.foir.dev, or your login domain for someone who signed in through it. Never ship a verifier to the browser. - Refresh token: longer-lived (30 days), rotated on every use; exchange it via
refreshTokenfor a fresh access token.
In the console
Setting Up Auth Providers
- Go to Access > Sign-in
- View the list of configured auth providers
- Click Add Provider to configure a new one:
- Key: unique identifier (e.g.,
google) - Name: display name (e.g., “Google Login”)
- Type: OAuth, OIDC, or other supported type
- Client ID / Secret: credentials from the provider
- Redirect URL: the callback URL for OAuth flows
- Enabled: toggle to activate or deactivate
- Priority: ordering for display in login UIs
- Key: unique identifier (e.g.,
- Save
A save proves the client
When you save an OAuth or OIDC provider’s client ID and secret, through the console, the API or foir push, Foir asks the provider’s token endpoint to exchange a code it never issued. A provider that knows the pair refuses only the code, and the save goes through. A provider that refuses the client (invalid_client) refuses the save, naming the client ID. That means the ID and the secret are not a pair it issued: usually they were copied from two different clients, or the secret was rotated. Copy both from the same client and save again.
If the provider can’t be reached when you save, the save still goes through, and the provider’s page says the client is not proven and why. Save the client again once the provider answers. A save that changes only the name, a scope or the priority doesn’t ask again. A public client has no secret, so there’s nothing to prove.
A read shows __redacted__ in place of a stored secret. Sending it back on an update keeps the stored secret, and on a create it’s refused, because it carries no secret.
Signup modes
Signup mode decides what self-serve registration does for people who have no
account yet. It is one setting per project, and it is enforced on the server:
every path that would create a user row from a self-serve flow checks it —
register, a one-time code sent to an address nobody has used before,
and a first sign-in through an external identity provider.
| Mode | What happens |
|---|---|
public | Anyone may register, subject to the restrictions policy below. The default. |
restricted | Registration is by invitation only. Nobody uninvited is made. |
waitlist | Nobody is made until the waitlist lets them in; they can join the queue instead. |
closed | Self-serve signup is off. Only somebody who manages the project’s users can add one. |
Whatever the mode, register and a request for a code answer an address
nobody holds exactly as they answer one somebody does, so neither tells anyone
which addresses have an account. What differs is the email: somebody new the
mode turns away is told there’s no account for the address, and whoever holds
an address somebody tried to register is told someone tried.
In public mode the hosted sign-in offers New here? Create an account. The
person proves the address with a one-time code sent to it, then chooses the
password they sign in with from then on. The password form never creates an
account: an address nobody holds gets the same answer there as a wrong
password. Joining is offered where the app takes a password, and it is no way
round the sign-in methods: where the project takes no code to sign in, somebody
who proves an address that already has a password is told to sign in with it.
The hosted sign-in always opens on the sign-in form, whatever the mode, because
most people who reach it have an account. Somebody new asks to join from the
link under the form, which reads New here? Join the waitlist in waitlist
mode. A site’s own Sign up or Join the waitlist button can skip that
step: link it to your login domain’s /signup (for example
https://login.example.com/signup), build the link with
hostedSignInUrl(config, returnTo, { signUp: true }), or, from an OpenID Connect
library, send prompt=create. The page then opens on what the mode gives
somebody new: joining in public mode, the waitlist in waitlist mode (with
Been let in? Create your account for whoever it let in), and the
invitation-only or closed notice in restricted and closed mode.
None of these touch sign-in. An existing user keeps logging in whatever the
mode says, because the check sits where a new row would be created and nowhere
else. Changing to closed stops growth; it does not lock anyone out.
A change of mode is served at the release, like every other project setting:
until then the hosted sign-in and the public API keep the mode that was last
released. To close signup in a hurry, release the change as you make it with
foir push --publish, or save it and release it from the unpublished list on
the console home page.
In public mode a restrictions policy narrows who counts as anyone:
- Block subaddresses requires the canonical inbox form, so a
+tagsubaddress, a Gmail dot variant and the googlemail alias domain all resolve to the address they belong to and cannot be used to register twice. - Block disposable domains rejects known throwaway mail providers.
- An allowlist and a blocklist of exact addresses (
user@domain.com), whole domains (domain.com) or wildcard subdomains (*.domain.com). A non-empty allowlist is exclusive: it admits only what it names, and beats the blocklist.
Set both from the console under Access > Sign-up, or declare them in
config as signupMode and signupRestrictions.
Session windows
A user session has two clocks, and they are not the same as the token lifetimes above.
- An idle window. The session slides: every authenticated request pushes its expiry out again. Default 30 days. A user who keeps visiting stays signed in indefinitely as far as this clock is concerned.
- An absolute ceiling. Measured from first login and never extended, whatever the user does. Default 90 days. This is what ends a session that a sliding window alone would keep alive forever — a credential that survives a stolen device should not be immortal.
Whichever fires first ends the session. In ordinary use it is the idle window: a daily visitor re-authenticates quarterly, someone away for a month is signed out well before the ceiling matters.
Both are configurable, and resolve through three layers, narrowest first:
- The project’s own setting —
sessionIdleDaysandsessionAbsoluteDays.NULLmeans inherit, so a project that has never been configured keeps following the fleet default when that moves. - The fleet default, a platform setting.
- The built-in constants, 30 and 90 days, which answer when a setting row is missing or unparseable — a bad edit must not be able to lock every user out.
If a project sets an idle window longer than the ceiling it inherits, the larger of the two wins rather than the mistake.
Token signing
Token signing keys and lifetimes are managed by Foir — access tokens are EdDSA, 15 minutes; refresh tokens are 30 days and rotate on use. There’s nothing to configure here. What you do control per project is which login methods are enabled (password, OTP), the project’s signup mode, and your auth providers, under Access > Sign-in and Access > Sign-up. A method that is off is refused, not only left off the page: by the hosted sign-in’s steps, and by login, register, requestOTP and a code brought back to its step from your app’s own form. An app’s loginMethods can turn one off for that app alone, where the sign-in comes through it. Where codes are off, a step still takes the code register mailed, and only that code.
Wrong passwords
Wrong passwords are counted for an address, whether or not anybody holds it, so the answers to a run of them say nothing about which addresses have an account. Ten in an hour from one IP block that IP for that address for an hour, and the right password is refused from there until then. Somebody guessing elsewhere can’t lock the owner out this way.
A project can also lock the address itself: with Lock accounts after failed
sign-ins on (locksAccountsAfterFailedSignIns in config), ten wrong
passwords in an hour from anywhere lock the address everywhere for an hour.
That stops guessing spread over many IPs, but anyone who knows an address can
then lock its owner out, so it is off by default. The right password clears
both counts. Turn it on under Settings > General, in User
authentication beside the sign-in methods.
An organization with a sign-in of its own makes this choice for its own
people, in its settings or with locks_accounts_after_failed_sign_ins on
UpdateOrganization. Until it chooses, it follows the project. An
organization that shares a sign-in, the project’s or another organization’s,
follows whoever keeps that sign-in: a password is the same wherever the
sign-in is used, so a lock kept by only one of the organizations sharing it
would be dodged by guessing at another.
Via the CLI
# List configured auth providers
foir auth-providers list
# Get details for a specific provider
foir auth-providers get <id>
# Create a new auth provider.
# --key, --name and --type are required; valid types are
# OAUTH2, OIDC, SAML, TOKEN_SSO, EXTERNAL.
# -d/--data carries the provider config only (NOT key/name/type/enabled).
foir auth-providers create \
--key google \
--name "Google Login" \
--type OIDC \
--enabled \
--data '{
"clientId": "your-client-id",
"clientSecret": "your-client-secret",
"redirectUrl": "https://yoursite.com/auth/callback"
}'
# Update an auth provider's config
foir auth-providers update <id> --data '{ "redirectUrl": "https://yoursite.com/auth/callback" }'
# Disable a provider
foir auth-providers update <id> --no-enabled
# Delete an auth provider
foir auth-providers delete <id>Via the API
Password sign-in
Every token-issuing mutation returns the same AuthResult { token, refreshToken, userId, email } (the token is a short-lived EdDSA access token you send as a Bearer).
mutation SignIn($email: String!, $password: String!) {
signIn(email: $email, password: $password) {
token
refreshToken
userId
email
}
}Registration
register returns a SignInStep and signs nobody in. Somebody new is made
with the password they chose and mailed a code, and bringing that code back to
the step’s route (below) proves the address, finishes
the account and returns the session:
mutation Register($email: String!, $password: String!) {
register(email: $email, password: $password) {
id
token
endpoint
expiresAt
}
}The answer is the same for an address that has an account already, and where the project takes nobody new; whoever holds the address hears about it by email instead. Until the code is used, the password works nowhere.
Sign out
Returns Boolean. It ends the provider tokens of the sign-in the user’s token belongs to: this device’s, and no other device’s. It does not revoke a refresh-token family and does not end a session. To end the refresh family too, POST the refresh token to /oauth/revoke, naming your auth client with client_id (or HTTP Basic, for a confidential client):
mutation SignOut {
signOut
}OTP Authentication
Ask for a one-time code. It answers the step the code is brought back to:
mutation RequestOTP($email: String!) {
requestOTP(email: $email) {
id
token
endpoint
expiresAt
}
}Every address is answered a step alike, so the answer says nothing of whether the address has an account. Bring the code back to the step’s own route with its token. It takes no key, since the token is the credential:
POST /v1/sign-ins/{id}/code
Content-Type: application/json
X-Foir-Token: <the step's token>
{"code": "123456"}It answers the session:
{
"accessToken": "eyJhbGciOi...",
"refreshToken": "rt_...",
"user": { "id": "usr_...", "email": "person@example.com" }
}A wrong code is answered 401 with "code": "UNAUTHENTICATED". A step’s code lapses with the step, at expiresAt, and a step signs somebody in once.
Password Reset
Request a reset (returns Boolean). Name your auth client with clientId, and a reset that finishes on Foir’s hosted page hands the user back to your app’s sign-in:
mutation RequestReset($email: String!, $clientId: String) {
requestPasswordReset(email: $email, clientId: $clientId)
}Redeem the emailed token on the reset’s own route. It takes no key, since the token is the whole credential:
POST /v1/password-resets/redeem
Content-Type: application/json
{"token": "reset_token_here", "newPassword": "newsecurepassword"}It answers the reset, with the session it opens where your project lets its own app sign people in:
{
"success": true,
"accessToken": "eyJhbGciOi...",
"refreshToken": "rt_...",
"user": { "id": "usr_...", "email": "person@example.com" }
}A spent or unknown token is answered 401 with "code": "UNAUTHENTICATED". Send projectId and clientId as well when the link names them, so the token is redeemed only where it was asked for.
Invitations and resets that start outside your app
An invitation or a reset email links to your app’s own pages (/accept-invitation, /reset-password) when the project has an App base URL. Without one, the links go to Foir’s hosted pages, on your app’s custom login domain when it has one. So the email always goes out.
To bring the user back into your app, give its auth client an initiate login URL: an address in your app that starts its sign-in. It is OIDC’s initiate_login_uri, set on the auth client in the console or as initiateLoginUri in your config. When the hosted page has done its part, it sends the user there with:
iss, the issuer to sign in with;login_hint, their email address;target_link_uri, the page they should land on, when there is one.
Your app starts a sign-in as it always does. For an invitation, the hosted sign-in asks the user to choose a password, accepts the invitation with it and signs them in, so they arrive in your app through a sign-in your app started.
An invitation names the auth client with clientId, and the page with returnTo:
mutation Invite($input: CreateAuthInvitationInput!) {
createInvitation(input: $input) { invitation { id } }
}
# { "input": { "email": "sam@example.com", "clientId": "popup", "returnTo": "https://popup.example/events/42" } }returnTo must be at the origin of one of the auth client’s own addresses: its redirect URIs, its post-login URL or its allowed origins. Anything else is refused when the invitation is made. Without an initiate login URL, or with no auth client named, the user accepts on the hosted page and is told to sign in from your app.
Inviting and reading invitations take members:write and members:read, the permissions for who stands in the project. Who sent an invitation is whoever made the request, and Foir records it.
An invitation can also give the user one of the project’s roles once they accept, named with roleId. They hold it across the project, or at the organization the request names with X-Org-Id. It’s decided as giving the role there directly is: you can give only a role you hold all of, and at an organization a key, or someone standing at an organization, can name only a role the project has made assignable inside one. A role disabled before the invitation is accepted isn’t given, and accepting says so.
Delivering the invitation yourself
Pass sendEmail: false and the answer carries the accept link and the token, for your app to deliver. That is the only time either is handed out: when Foir mails the invitation, it keeps both to the email, because the token reaching that inbox is what proves the address when the user accepts.
So a token you deliver proves nothing about the address on its own. A new user who accepts one with a password is signed in with it. One who accepts without a password is made, waiting to prove their address, and signs in later with a code sent to it. Someone who already has an account with the address joins only while signed in as themselves.
Someone who already has an account is never given a password by accepting, whichever way the invitation reached them. They join and sign in as they always do.
Update Password (Authenticated)
Returns Boolean:
mutation UpdatePassword($currentPassword: String!, $newPassword: String!) {
updatePassword(
currentPassword: $currentPassword
newPassword: $newPassword
)
}Token Refresh
Refresh tokens rotate on every use — persist the new one before responding to the user:
mutation RefreshToken($refreshToken: String!) {
refreshToken(refreshToken: $refreshToken) {
token
refreshToken
userId
email
}
}Current User
query CurrentUser {
currentUser {
id
email
status
emailVerifiedAt
createdAt
}
}Auth Providers
List available providers for your sign-in UI:
query ListProviders {
authProviders {
key
name
type
isDefault
}
}OAuth Callback
After the user completes the OAuth flow, bring the code and state back to the step signInWithProvider answered, with its token:
POST /v1/sign-ins/{step.id}/provider
Content-Type: application/json
X-Foir-Token: <the step's token>
{"providerKey": "google", "code": "auth_code_from_redirect", "state": "state_parameter"}It answers the session:
{ "userId": "usr_...", "email": "person@example.com", "accessToken": "eyJhbGciOi...", "refreshToken": "rt_..." }Where the provider names an address somebody already holds and does not prove it is theirs, the sign-in waits for a code sent to that address. The answer is 412 with "providerSignIn": {"code": "link_code_sent", "pending": "..."}. Post the code to POST /v1/sign-ins/{step.id}/link with {"pending": "...", "code": "..."}, or ask for a fresh one at POST /v1/sign-ins/{step.id}/link/resend with {"pending": "..."}, each with the same token.
What the hosted sign-in sends back
When the hosted sign-in can’t finish a sign-in, it sends the browser back to your app’s callback with your state, an OAuth error and a stable code in foir_error (also in error_description). It never shows the person a page of JSON. error is access_denied when the person was refused, temporarily_unavailable when the provider they chose couldn’t be reached, and server_error when the sign-in failed on the server side, such as a provider refusing Foir’s request. The codes include signup_closed, user_cap_reached, account_unavailable, account_not_here, email_unavailable, provider_refused, provider_unavailable, provider_exchange_failed, provider_named_no_address and mfa_required.
When a provider sign-in was connected to an existing account on the way in, the return carries foir_connected with the provider’s key, beside the usual code and state. The account’s owner is also emailed.
hostedSignInNoticeOf from @foir/sdk/auth reads either one and gives you a sentence to show. Switch on code to use your own words:
import { hostedSignInNoticeOf } from '@foir/sdk/auth';
const notice = hostedSignInNoticeOf(window.location.href, { shopify: 'Shopify' });
if (notice?.kind === 'refused') showError(notice.message);
if (notice?.kind === 'connected') showNote(notice.message); // "Your Shopify sign-in is now connected to your account."Auth Configuration
Query the project’s auth settings to build dynamic login forms:
query AuthConfig {
authConfig {
passwordEnabled
otpEnabled
providers {
key
name
type
}
}
}Signup context and waitlist
authConfig says which login methods exist. It does not say whether a stranger
may register, which is the other half of what a signup form needs. Read the
project’s signup mode before you render one:
query SignupContext {
signupContext {
signupMode # PUBLIC | RESTRICTED | WAITLIST | CLOSED
}
}On WAITLIST, offer the queue instead of the form:
mutation JoinWaitlist($email: String!) {
joinWaitlist(email: $email)
}joinWaitlist is a signup path in its own right, so it is present in every
project’s schema regardless of the password and OTP flags. It is rejected
unless the project is in waitlist mode: the mode is checked on the server, not
by whether the field is published. It returns true for every address it
accepts, whether the address was queued, was already let in or already has an
account, so it can’t be used to find out who has signed up. What differs is the
email the address is sent.
A project manager approves entries from the console. An approval lets the address in: from then on it can sign up by any way in your app offers (a one-time code, or a password where your app takes one), and it’s emailed a link to your app’s sign-in. Denying an approved entry takes the approval back until the address has signed up.
Complete sign-in example
// 1. Check auth config to know which methods are available
const { data: config } = await client.query({ query: AUTH_CONFIG });
// 2. Sign in with email and password
const { data: signedIn } = await client.mutate({
mutation: SIGN_IN,
variables: { email, password }
});
const session = signedIn.signIn;
if (session) {
// 3. Store tokens (prefer an httpOnly cookie set from your server over localStorage)
localStorage.setItem('accessToken', session.token);
localStorage.setItem('refreshToken', session.refreshToken);
// 4. Use the access token for authenticated requests
const { data: user } = await client.query({
query: CURRENT_USER,
context: {
headers: {
Authorization: `Bearer ${session.token}`
}
}
});
}Using Access Tokens
Include the access token in subsequent requests:
curl -X POST https://api.foir.dev/graphql \
-H "Content-Type: application/json" \
-H "x-api-key: foir_pub_..." \
-H "Authorization: Bearer eyJhbGc..." \
-d '{"query": "{ currentUser { id email } }"}'Config System
Auth providers can also be defined in foir.config.ts using defineAuthProvider. See the Configuration reference for details.
Project Email & Brand
Every project has a brand block that controls how the project’s emails to its users (welcome, password reset, sign-in codes, invitations) look and where they link. These are project-level settings, not per-user.
| Field | Purpose |
|---|---|
displayName | Human-readable project name shown in emails (“Bob’s Country Bunker”) |
logoUrl | URL of the project logo embedded in email templates. Defaults to app.foir.io/logo.png if unset. |
primaryColor | Brand colour applied to email buttons and accents (hex string, e.g. #2c4433) |
fromName | Display name on the From header (From: Bob's Country Bunker <noreply@…>) |
replyTo | Address users reach when replying to platform emails |
supportEmail | Address shown to users in error states (“Contact support@…”) |
appBaseUrl | Public base URL of your storefront/portal, used as the base for links in emails ({appBaseUrl}/reset-password?token=…). Without one, account emails (password reset, sign-in code, invitation, welcome) link to Foir’s hosted pages instead. |
welcomeEmailEnabled | Toggle: send a welcome email once a new user proves their address. On by default. |
Configuring brand fields
In the console: Settings > General, under Branding and the email sections. Fill in display name, logo, primary colour, support address, and your user portal URL.
If appBaseUrl is unset, account emails link to Foir’s hosted pages (see Invitations and resets that start outside your app). An email whose copy links into your app, which only an App base URL can address, is refused when it is sent until one is set.
Welcome emails
When welcomeEmailEnabled is true, the platform sends a welcome email with the project’s branding to every new user once they prove their address. Toggle it off if your application sends its own welcome email and you don’t want a duplicate.
Email service
Foir sends every email to a project’s users (welcome, password reset, sign-in codes, invitations) through a single outbound pipeline. Templates are project-aware: every send pulls the project’s brand block to render the template. If you maintain multiple projects, each project’s emails use its own brand independently.
Best Practices
- Always handle token refresh — implement automatic refresh when access tokens expire.
- Query auth config first — build login UIs dynamically based on the enabled methods (
passwordEnabled,otpEnabled,providers). A method that is off is refused withFAILED_PRECONDITIONandextensions.signIn.codeset topassword_sign_in_offorcode_sign_in_off; the SDK’ssignInRefusalOf(error)reads it. - Use OTP for passwordless flows — simpler for users and avoids password management.
- Verify tokens server-side — validate the EdDSA access token against the JWKS endpoint (
https://api.foir.dev/.well-known/jwks.json) or use thecurrentUserquery to validate sessions. - Choose your session windows: token lifetimes are fixed, and the session windows are where you balance security with user convenience.