Hosted sign-in
Foir hosts the sign-in for your app. Your users sign in on your project’s login page, in your brand and on your own login domain if you have one, with a password, an emailed code, a passkey or a provider such as Google. Your app gets their tokens through the standard OpenID Connect code flow, so there is no password storage and no sign-in screen of your own to build or secure.
The app is an auth client. It signs in a project’s users, or your workspace’s team, and nobody else: there is no general Fóir account that people bring from one product to another. The people your app signs in are yours.
Ways to connect
| You have | Use |
|---|---|
| A server app and no OpenID Connect library | The SDK’s code flow: beginSignIn and completeSignIn from @foir/sdk/auth |
| An OpenID Connect library | Any OpenID Connect library: openid-client, Auth.js, go-oidc, Spring Security, AppAuth |
| A tool with a generic OpenID Connect login, such as a help desk or a dashboard | Connect an existing tool: a client ID and a secret in the tool’s settings |
| An app on the same registrable domain as your login domain | The hosted session: the login domain’s session cookie, traded on your server for a token |
The first three are the same flow at the same endpoints (/oauth/authorize and /oauth/token), so an app can start with the SDK and move to a library later without changing anything in Foir.
Register your app
Register the auth client in foir.config.ts, or in the console under Access, Sign-in on the Auth clients tab. An auth client that signs in your workspace’s team is registered in the workspace console under Sign-in, on its Auth clients tab (Apps that sign in your team).
// foir.config.ts
import { defineConfig, defineAuthClient } from '@foir/cli/configs';
export default defineConfig({
name: 'Eide Clothing',
authClients: [
defineAuthClient({
clientId: 'eide-clothing-storefront',
name: 'Eide Clothing Storefront',
redirectUris: [
'https://eide.clothing/auth/callback',
'https://staging.eide.clothing/auth/callback',
],
grants: ['*'],
}),
],
});foir pushfoir push creates the auth client on first push and updates it on later pushes. Like every definition, a new auth client signs nobody in until a release carries it: the login page answers app_not_recognised until then, and the console’s list says Not released, with Publish to release it. foir push --publish releases it as it pushes. Disabling an auth client in the console ends its users’ sessions and tokens straight away: the public API stops honouring the access tokens it issued, an open subscription socket included, rather than waiting for them to expire.
Fields:
clientId: unique per project. It goes in your redirect URLs and names your app in the console.name: the name the login page and the consent page show.redirectUris: an exact-match list, trailing slashes included. One exception: a literalhttp://127.0.0.1orhttp://[::1]entry matches any port, for native clients that cannot reserve one. Register it without a port,http://127.0.0.1/callback, and everything else still matches exactly.grants: the most a sign-in through this app may carry of what the person’s roles give them, in the names of the permission catalogue. The list gives nobody anything: a person holds what their roles give, and the list decides how much of it a token minted for this app carries. So it may hold a wildcard, which a role may not.['*']is an app that is not narrowed, and'records:*'carries whatever its users hold over records. An entry covers its narrower forms:operations:executecovers a role’soperations:execute:checkout, andrecords:writecoversrecords:write:order. A role’s grant wider than the list is cut to it, never dropped whole: a role’srecords:write, through a list namingrecords:write:order, carriesrecords:write:order.[]is an app whose sign-ins carry nothing of what its users’ roles give, for an app that only needs to know who someone is.loginMethods(optional): narrows the project’s sign-in methods for this app, such as no password for this app only. It never widens them.firstParty(optional): whether your project runs this app. A sign-in through an app the project runs asks nobody to agree to it. Leave it off for an app someone else runs, and each person is asked once (Consent).logo(optional): the app’s own logo, which the consent page shows beside its name, so a person can see whose app is asking. Exactly one offile, one of the project’s public images by its file id, orurl, an https address, withaltsaying what it shows. In the console, the auth client’s form picks or uploads the image. An app of your workspace has no project to keep files, so it names an address.homepageUrl(optional): the app’s homepage, an https address. The consent page links the app’s name to it.confidential(optional): whether the app is a server that keeps a client secret. Leave it off for an app in a browser or on a phone. See Apps that keep a secret.
Branding lives on the project, so the auth clients of one project share its login page’s look.
The issuer
| Where | Issuer |
|---|---|
| Production | https://api.foir.dev |
| A project’s verified login domain | The domain’s origin, such as https://login.your-domain.com |
The discovery document is at {issuer}/.well-known/openid-configuration. If your project has a verified login domain, use the domain as the issuer: everybody who signs in through it gets tokens that carry it as iss, and keeps it when they refresh, so a library that discovers at the domain checks the issuer it was given, as OpenID Connect requires. The OpenID Connect reference lists every endpoint, parameter and claim.
The SDK’s code flow
For a server app (a Worker, Oxygen, Node) that has no OpenID Connect library, @foir/sdk/auth runs the code flow in two calls. beginSignIn finds the endpoints from discovery and builds the authorization URL with a PKCE S256 challenge, a state and a nonce. completeSignIn checks the callback, redeems the code and checks the ID token’s issuer, audience, nonce and expiry.
import { beginSignIn, completeSignIn, CodeFlowError } from '@foir/sdk/auth';
const foir = {
issuer: 'https://login.eide.clothing',
clientId: 'eide-clothing-storefront',
redirectUri: 'https://eide.clothing/auth/callback',
};
// Your sign-in route.
const pending = await beginSignIn(foir, { scope: 'openid profile email' });
session.set('foirSignIn', { state: pending.state, codeVerifier: pending.codeVerifier, nonce: pending.nonce });
return redirect(pending.url);
// Your callback route.
try {
const tokens = await completeSignIn(foir, request.url, session.get('foirSignIn'));
session.unset('foirSignIn');
session.set('foirTokens', tokens); // accessToken, refreshToken, idToken, claims
return redirect('/');
} catch (error) {
if (error instanceof CodeFlowError && error.code === 'access_denied') return redirect('/signed-out');
throw error;
}Keep what beginSignIn returns on your server, or in an HttpOnly cookie scoped to the callback: never in a URL or in browser JavaScript. The verifier redeems the code once, and a code and state intercepted at the redirect are no use without it. beginSignIn also takes org, the organization the person signs in to when your app serves several, prompt and loginHint. prompt: 'create' opens the page on the project’s way in for somebody new, for a Sign up or Join the waitlist button.
Any OpenID Connect library
Any library works when it is configured with:
- discovery from the issuer;
- the authorization code flow, with PKCE (S256) for a public app;
- client authentication
nonefor a public app, orclient_secret_basicorclient_secret_postwith its secret for a confidential one; - ID tokens signed RS256, which is every library’s default.
openid-client
openid-client (version 6) on a Node server:
import * as client from 'openid-client';
const config = await client.discovery(
new URL('https://api.foir.dev'),
'your-client-id',
undefined,
client.None(), // a public client: PKCE, no secret
);
// Start a sign-in. Keep the verifier, nonce and state in the user's session.
const codeVerifier = client.randomPKCECodeVerifier();
const nonce = client.randomNonce();
const state = client.randomState();
const signInUrl = client.buildAuthorizationUrl(config, {
redirect_uri: 'https://shop.example.com/auth/callback',
scope: 'openid profile email offline_access',
code_challenge: await client.calculatePKCECodeChallenge(codeVerifier),
code_challenge_method: 'S256',
nonce,
state,
});
// Redirect the browser to signInUrl.
// On your callback route:
const tokens = await client.authorizationCodeGrant(config, new URL(req.url, 'https://shop.example.com'), {
pkceCodeVerifier: codeVerifier,
expectedNonce: nonce,
expectedState: state,
});
const claims = tokens.claims(); // sub, email, name, auth_time, amr, ...
// Later: who they are now, and fresh tokens.
const me = await client.fetchUserInfo(config, tokens.access_token, claims.sub);
const refreshed = await client.refreshTokenGrant(config, tokens.refresh_token);Auth.js
Auth.js takes Foir as a custom OpenID Connect provider. The same object works in @auth/express, next-auth and the other framework packages:
const foir = {
id: 'foir',
name: 'Foir',
type: 'oidc',
issuer: 'https://api.foir.dev',
clientId: 'your-client-id',
client: { token_endpoint_auth_method: 'none' },
checks: ['pkce', 'state', 'nonce'],
authorization: { params: { scope: 'openid profile email' } },
};Register https://your-app.example.com/auth/callback/foir as a redirect URI. Auth.js reads the person’s email and name from the ID token. Set idToken: false on the provider if you would rather it called the userinfo endpoint.
Other libraries
In Spring Security, set client-authentication-method: none on a public app’s registration, or client_secret_basic with its client-secret on a confidential one’s. go-oidc’s NewProvider and Verifier need nothing beyond the client ID. AppAuth is a public client already; register its redirect as a claimed HTTPS link or a loopback address (http://127.0.0.1/callback matches any port).
Apps that keep a secret
An app whose code runs only on a server you control can keep a client secret: a server-rendered web app, or a tool with a generic OpenID Connect login. Register it as confidential (confidential: true, or Confidential app (keeps a client secret) in the auth client’s form). An app in a browser or on a phone ships its code to the people who use it, so it can’t keep a secret; it stays public and proves each sign-in with PKCE.
A confidential app authenticates with one of its secrets wherever it trades a code, refreshes or revokes: by HTTP Basic (client_secret_basic) or as client_secret in the form (client_secret_post). Without a live secret it is refused invalid_client, so it signs nobody in until it has one. Because its code is traded only with its secret, it may leave PKCE out; a challenge it sends is checked as a public app’s is.
Make a secret in the auth client’s form or with foir auth-clients secrets create <clientId>. Foir shows it once and keeps only its hash. An app can hold several secrets at once, so you rotate one without a gap: make the new one, move the app to it, then revoke the old one with foir auth-clients secrets revoke <clientId> <id> or in the form. Disabling the app, or binding it to another place, revokes all its secrets. A config declares confidential and never carries a secret. Connect an existing tool walks through it with Grafana and oauth2-proxy.
The hosted session
When your app and your login domain share a registrable domain (shop.example.com and login.example.com), the login domain’s session cookie reaches your app’s server. Send the person to the login domain with hostedSignInUrl (with { signUp: true } for somebody new, which opens /signup), then trade the cookie on your server for a short-lived token with fetchHostedSession. The cookie is the lasting credential, and there is no refresh token to keep. First-party sessions walks through it.
Scopes
openid asks for an ID token. profile adds the person’s name, picture and language, and email their address and whether it is verified. offline_access is accepted; every sign-in gets a refresh token anyway, which lasts up to 30 days and ends when the person signs out.
The rest of the scope names permissions, in the same names as your roles, and is kept to the app’s grants. A sign-in that names none asks for everything the app lists, and OpenID Connect’s own scope values never count as permissions. A sign-in that asks for more than the list is given what the two share. A scope that is neither a permission nor one of those values is refused invalid_scope by name, and so is a request for permissions that share nothing with the list.
Call the public API
await fetch('https://api.foir.dev/graphql', {
method: 'POST',
headers: {
authorization: `Bearer ${tokens.accessToken}`,
'x-api-key': PUBLIC_API_KEY,
'content-type': 'application/json',
},
body: JSON.stringify({ query: '{ currentUser { id email } }' }),
});The key identifies your app and the bearer token the person signed in. Every request is scoped to them by the token’s sub claim, their user id. Access tokens last 15 minutes. Refresh at the token endpoint (grant_type=refresh_token), or with the public API’s refreshToken mutation; refresh tokens rotate on every use, and presenting one that was already rotated ends the whole family, so save the new one before you answer the person.
Consent
A sign-in through an app that its level does not run asks the person to agree to it first. A project runs the apps it marks firstParty, and a workspace runs the team apps it marks This workspace runs this app.
- The first time someone signs in through the app, the consent page shows who is asking (the app’s name, with its logo and homepage where it has them), what it asks to carry for them, said in words, and where it will act, with the project’s brand. They are shown, and agree to, only what they hold something of. A consent is their limit on the app and gives them nothing.
- The token carries what they hold, kept to the app’s list, to what the sign-in asked for and to what they agreed. A later sign-in that asks for something they have not agreed to asks them again, for that.
- When they take their consent back, the app’s refresh tokens for them are revoked at once and the next refresh fails with
invalid_grant. - Each person can see the apps they have agreed to, each with its logo, and take any of them back: your team on their Fóir account page, and a project’s users on your own account page, through
myAuthorizedApps(clientName,clientLogoUrl,clientLogoAlt,clientHomepageUrl) andrevokeAuthorizedApp.
Apps that sign in your team
An auth client can sign in your workspace’s team instead of a project’s users: a back-office tool, say. It uses the same flow. What differs is where it is registered and where its tokens act.
- Register it in the workspace console under Sign-in, on the Auth clients tab, not through
foir push: a push is scoped to one project, and this app belongs to the workspace. A workspace manager can create one. - Its
grantsare read as a project app’s are. It has to name at least one entry, and whoever writes it can list only what they hold themselves. - Every token it issues is for your workspace. The project is the one the person chooses on the login page, from the projects of your workspace they can reach, or the app’s own project when it was registered with one. Somebody with no access to your workspace is refused
access_denied. - The token’s
audis your client ID, and itsgrantssay what it carries: what the team member holds there, kept to your app’s list, to what the sign-in asked for and to what they agreed. A team member who holds none of what your app asks for is refusedaccess_denied, and the refusal names what they do not hold. - The public API checks each token against live state: the auth client must still be enabled and still list what the token carries, and the team member must still have their access and, for an app your workspace does not run, their consent. Anything that ends their authority stops the affected tokens straight away, and an open subscription socket closes with code
4402.
Invitations and password resets
Set the auth client’s Initiate login URL to an address in your app that starts its sign-in. When someone accepts an invitation or resets their password on Foir’s pages, Foir sends them there with iss, login_hint and target_link_uri, and your app starts a sign-in as it always does. Without the address, the person finishes on Foir’s page and is told they’re set up.
Signing out
Discovery names the end_session_endpoint. Send the browser there with id_token_hint (an ID token Foir gave this sign-in, which may be expired), post_logout_redirect_uri (on the same origin as one of the app’s redirect URIs) and state. Foir ends the session the person signed in with, and its refresh tokens stop working. To end only a refresh family from your server, POST the refresh token to /oauth/revoke with your client ID, and its secret if the app is confidential (RFC 7009 ); only the app a token was issued to may revoke it.
Moving or deleting an app
An auth client is bound to one organization of its project, or to the whole project. Binding it somewhere else ends what it issued under the old binding: its users’ consents, the sessions signed in through it and their refresh tokens.
foir auth-clients rebind my-app --to-org org_123
foir auth-clients rebind my-appThe second command binds it to the whole project. Deleting an auth client frees its client ID and ends the same things; if a release has carried it, the next release deletes it. You can’t delete an auth client that a login domain fronts: remove the domain, or move it to another auth client, first.
Verify tokens yourself
A backend can verify access tokens without asking the API:
import { jwtVerify, createRemoteJWKSet } from 'jose';
const jwks = createRemoteJWKSet(new URL('https://api.foir.dev/.well-known/jwks.json'));
const { payload } = await jwtVerify(accessToken, jwks, {
issuer: 'https://api.foir.dev', // or your login domain, for somebody who signed in through it
audience: 'eide-clothing-storefront',
});
// payload.sub is the user id; payload.tenant_id, payload.project_id, payload.grantsVerify on a server, never in the browser. Somebody who signed in through your login domain carries the domain as iss, so a backend that serves both checks the issuer the token was given against the two it trusts.
When something goes wrong
Errors come back to your redirect URI as error and error_description, with your state:
error | What happened |
|---|---|
login_required | You sent prompt=none and nobody who may go on is signed in, or their sign-in is older than max_age. |
consent_required | You sent prompt=none and the person has not agreed to what the app asks. |
interaction_required | You sent prompt=none and the sign-in needs the person on a page, to choose a project or prove a second factor. |
access_denied | The person declined, or their organization is not active, or the provider they chose refused them. foir_error says which. |
temporarily_unavailable | The provider the person chose couldn’t be reached. Asking again later may work. |
server_error | The sign-in failed on the server side. foir_error says what. |
invalid_scope | The scope named a permission the app’s grants cover none of, or something that is no permission. |
request_not_supported | You sent a request object. Send the parameters on the query instead. |
A redirect URI the app does not list never receives an error: the person sees Foir’s own error page instead.
Common questions
Can one person hold sessions with several apps? Yes. Each client ID issues its own token chain, and revoking one leaves the others.
What if my redirect URI changes?
Push the new redirectUris list. Old URIs stop being accepted on the next sign-in, with no grace period, so time it with your deploy.
Can I read the person’s email from the access token?
No. The access token says who the person is (sub), where it acts (tenant_id, project_id) and what it carries (grants), and names no address. The ID token and the userinfo endpoint carry the email where the sign-in asked for email.