App sign-in library
Check app sign-in tokens in a Node.js backend, get a Shell app's app token, and look up a standalone app's sign-in settings in the browser.
@groundfloorcloud/app-auth checks, in your backend, that a request comes from a user signed in to your app. In the browser, it gets a Shell app's app token for its backend, and gives a standalone app its sign-in settings. It's for your app's users, not your team.
npm install @groundfloorcloud/app-authIt's open source under the MIT licence. It needs Node.js 20.19 or later and works with ESM and CommonJS. Its one dependency is jose; the browser entry, @groundfloorcloud/app-auth/browser, doesn't include it.
Check tokens in your backend
import { requireAppUser, verifyAppToken, AppAuthError } from "@groundfloorcloud/app-auth";
app.use("/api", requireAppUser()); // 401 without a valid app token
app.post("/api/posts", requireAppUser({ roles: ["editor"] }), handler); // 403 without the role
try {
const user = await verifyAppToken(token);
} catch (err) {
if (err instanceof AppAuthError) res.status(err.status).json({ error: err.code });
}| Function | What it does |
|---|---|
requireAppUser(options?) | Express-style middleware. Reads Authorization: Bearer <token>, checks it, and puts the user on res.locals.appUser and req.appUser. Answers 401 with {"error": "<code>"} and WWW-Authenticate: Bearer, or 403 for a missing role or company |
createAppTokenVerifier(options?) | Returns a function that checks a token and resolves to the user. Reads its settings once, so a missing setting fails when your server starts |
verifyAppToken(token, options?) | Checks one token in a single call |
verifyShellToken(token, options?), createShellTokenVerifier(options?) | The same for a Shell app's backend that gets the Shell site token (azp shell) with Groundfloor sign-in. Every check applies except the audience. Pass issuer. Shell site tokens are accepted until Groundfloor announces a date to retire them; prefer app tokens. See Accept both while you move over |
hasAnyRole(user, roles) | true if the user has at least one of the roles |
bearerToken(header) | The token from an Authorization header, or null |
readRoles(claims), readOrganization(claims) | Read roles, and companies as { aliases, ids }, from a token's claims. These list every company the user belongs to; don't pick the company to act in from them |
activeOrganization(claims) | The company the session acts in, as { id, alias }, or null. See The active company. In 0.3.0 and later |
In a Shell app's backend there are no GROUNDFLOOR_AUTH_* variables: pass issuer and audience: "app-<app-id>" yourself. See Check an app token.
An app token is accepted only if it's signed with RS256 by a key from the JWKS URL, iss equals the issuer exactly, aud contains the app's client ID, azp equals it (a token without azp is refused), exp hasn't passed (with 30 seconds of clock leeway by default, at most 60; nbf and iat, when present, get the same leeway), typ (when present) is Bearer, sub is present, and there's no x-client-key or x-userid claim. Those claims mark Groundfloor's own Coderunner management and developer tokens, which are refused with wrong_token_type. The keys are cached for 10 minutes and fetched again, at most every 30 seconds, when a token names a key the cache doesn't have.
The user
| Field | What it is |
|---|---|
sub | The user's ID. Store and match their records by it, not by email |
roles | The user's roles, without offline_access, uma_authorization and default-roles-*. A malformed claim reads as no roles |
organization | The aliases of the user's companies (tenants), with Multi-tenant on; otherwise empty |
organizationIds | The companies' IDs, when the token has them |
activeOrganizationId | The ID of the company the session acts in, or null. See The active company. In 0.3.0 and later |
email | The user's email address, or null |
clientId | The client the token was issued to (azp) |
claims | Every claim in the token |
Any user of the workspace can sign in to any of its apps, so always check roles. With Multi-tenant on, a role applies in every company the user belongs to: filter reads and writes by the active company too, or use requireOrganization.
The active company
activeOrganization(claims) and user.activeOrganizationId give a company only when the token's organization claim names exactly one company with its ID ({"acme": {"id": "…"}}). Several companies, aliases without IDs, or no claim give null: act in no company rather than guess one. The claim only says which company the user acts in, so still check in your own data that the user belongs to it.
import { activeOrganization } from "@groundfloorcloud/app-auth";
const active = activeOrganization(user.claims); // { id, alias } or null
if (!active) return res.status(403).json({ error: "no_active_company" });Options
Options you pass win over environment variables.
| Option | Default |
|---|---|
issuer | GROUNDFLOOR_AUTH_ISSUER |
audience | GROUNDFLOOR_AUTH_AUDIENCE (the app's client ID, app-<app-id>) |
jwksUrl | GROUNDFLOOR_AUTH_JWKS_URL, else {issuer}/protocol/openid-connect/certs. https only, or http on localhost |
requireOrganization | false. true needs any company; a tenant's alias or ID needs that company to be the active company. Otherwise 403 organization_required |
clockToleranceSeconds | 30. Any value from 0 to 60; more than 60 is refused |
jwksCooldownMs, jwksCacheMaxAgeMs, jwksTimeoutMs | 30000, 600000, 5000 |
env | process.env |
requireAppUser also takes roles (the user needs at least one), shell: true to check Shell site tokens instead, and onError(err, req) for logging. Never log the token itself.
Environment variables
Groundfloor sets these on a standalone app's running main Service when it deploys, unless you set them yourself, while app sign-in is switched on. They're your backend's runtime environment, not variables in your front end's build. See Find your issuer and client ID.
| Variable | Value |
|---|---|
GROUNDFLOOR_AUTH_ISSUER | The issuer of the app's tokens |
GROUNDFLOOR_AUTH_JWKS_URL | {issuer}/protocol/openid-connect/certs |
GROUNDFLOOR_AUTH_AUDIENCE | app-<app-id> |
GROUNDFLOOR_AUTH_CLIENT_ID | app-<app-id>, for the front end's sign-in |
GROUNDFLOOR_APP_ID | The app's ID |
Errors
AppAuthError has a code and the HTTP status to answer with:
| Status | code |
|---|---|
401 | missing_token, invalid_token, token_expired, wrong_issuer, wrong_audience, wrong_client, wrong_token_type, missing_subject |
403 | role_required, organization_required |
500 | config: a setting is missing or wrong in your backend |
503 | jwks_unavailable: the signing keys couldn't be fetched |
getAppToken() throws AppAuthError too, with its own codes and Groundfloor's status, including 404, 409 and 429. See Get a token for a Shell app.
Get sign-in settings in the browser
import { getAppAuthConfig } from "@groundfloorcloud/app-auth/browser";
const cfg = await getAppAuthConfig({ controlPlaneUrl: "https://platform.groundfloor.cloud" });
// { issuer, clientId, realm, redirectUri: "https://<this host>/auth/callback" }, or nullgetAppAuthConfig asks Groundfloor for the sign-in settings of the standalone app on the page's own host, and resolves to null when that host has no app sign-in. Pass controlPlaneUrl, for example from your build config. The lookup accepts calls from any web address, so it works on your custom domains. Hand the result to an OpenID Connect library with PKCE; see Sign users in from the browser.
| Option | Default |
|---|---|
controlPlaneUrl | Groundfloor's main API address. Pass https://platform.groundfloor.cloud so it matches the cell your workspace is on |
host | The page's host (location.hostname). On a local dev server, pass the app's real host; redirectUri is then https://<host>/auth/callback, so use your dev server's own callback address instead |
callbackPath | /auth/callback |
fetch, signal | The browser's fetch, no abort signal |
Get a token for a Shell app
getAppToken() is in @groundfloorcloud/app-auth 0.2.0 and later (npm install @groundfloorcloud/app-auth@latest); app tokens are rolling out. It needs Groundfloor sign-in.
import { getAppToken } from "@groundfloorcloud/app-auth/browser";
const res = await fetch(`${API_URL}/api/posts`, {
headers: { Authorization: `Bearer ${await getAppToken()}` },
});It swaps the signed-in user's Shell site token for an app token for your app, with POST https://platform.groundfloor.cloud/v1/workspaces/{workspace_id}/apps/{app_id}/token (see the Apps API), and returns the token. Send it only to your own backend, which checks it with requireAppUser({ issuer, audience: "app-<app-id>" }) or verifyAppToken. Groundfloor's APIs refuse app tokens: keep sending them the Shell site token.
| Option | Default |
|---|---|
appId | The app the Shell has open (window.__GF_APP_ID__). Pass your app's ID if your code can run while another app is open |
controlPlaneUrl | The Shell's API address (window.__GF_CONTROLPLANE_URL__). https only, or http on localhost |
workspaceId | The Shell's workspace (window.__GF_WORKSPACE_ID__) |
getShellToken | The Shell's window.__GF_GET_ACCESS_TOKEN__ |
forceRefresh | false. true skips the cache, for example after your backend answered 401 |
fallbackToShellToken | false. See below |
fetch | The browser's fetch. A call that passes its own fetch gets its own cache, kept per fetch function: tokens, requests in flight, 429 waits and fallback decisions. It never sees tokens other calls got, and its tokens are never returned to calls without that same function, so another app on the Shell site can't plant a token for yours. Pass the same function every time to keep the caching |
Inside the Shell every option has a default, so await getAppToken() is enough. Outside it, pass all four of appId, controlPlaneUrl, workspaceId and getShellToken.
- The token has
audandazpequal toapp-<app-id>, the user'ssub,email,rolesand, with Multi-tenant on,organization. It lasts at most 5 minutes, and never longer than the user's Shell sign-in. - Caching. Tokens are cached per app and user (and per
fetchfunction, if you pass one), and replaced 30 seconds before they expire (or at half their lifetime, if that's shorter); a token is never used past its expiry. Calls at the same time share one request. CallgetAppToken()before every request.clearAppTokenCache()forgets every cached token. - Rate limits. By default Groundfloor gives each user 20 app tokens a minute per app, and 60 a minute across apps. After a
429it doesn't ask again untilRetry-Afterhas passed (60 seconds if the answer has none): in between it returns the cached token if it's still valid, or throwsrate_limitedwitherr.retryAfterSeconds. Don't retry in a loop. - Refusals throw an
AppAuthError. It never quietly returns the Shell site token instead.
code | status | Why |
|---|---|---|
missing_token | 401 | Nobody is signed in to the Shell |
shell_token_expired | 401 | The Shell site token has expired; the user signs in again |
invalid_token | 401 | Groundfloor didn't accept the Shell site token |
app_token_requires_shell_token | 403 | Not a Shell site token of this workspace, for example a team or M2M token |
app_token_forbidden | 403 | The user has no role in the workspace |
app_not_found | 404 | No such app in this workspace, or the user can't open it (X-Groundfloor-Reason: app_not_found) |
app_token_route_missing | 404 | A 404 without that reason: Groundfloor at controlPlaneUrl doesn't offer app tokens yet, or controlPlaneUrl points somewhere else |
app_tokens_disabled | 409 | App tokens aren't switched on for your cell yet |
app_token_requires_groundfloor_login | 409 | The workspace signs users in with its own identity provider: check that provider's tokens instead |
app_token_requires_shell_federated_app | 409 | Not a Shell app. Standalone apps sign users in themselves |
app_archived | 409 | The app is archived |
app_token_refused | 409 | Another refusal; err.reason says which |
rate_limited | 429 | Too many requests; see err.retryAfterSeconds |
app_token_key_unavailable | 503 | App tokens are briefly unavailable; try again later. Can happen for a short time right after app tokens are switched on |
app_token_unavailable | 503 | Groundfloor couldn't be reached, or answered something unexpected |
config | 500 | A setting is missing (outside the Shell, pass all four), or controlPlaneUrl isn't https |
err.reason holds Groundfloor's X-Groundfloor-Reason header, when it sent one.
fallbackToShellToken: true (off by default) returns the Shell site token instead, and remembers that for 5 minutes, only when the answer is app_tokens_disabled or app_token_requires_groundfloor_login. It doesn't apply to app_token_route_missing. Use it only for an app that may run where app tokens aren't available, and only if your backend accepts both. Every other refusal still throws.
App tokens don't separate apps in the browser
Every app on a Shell site runs in the same browser window, so any of them can get app tokens for any app the signed-in user can open. App tokens stop a token sent to one backend being used on Groundfloor's APIs or another app's backend; they don't stop apps reaching each other in the browser. Install only apps you trust, and check roles in every backend. See Every app on your Shell site can use the user's token.
Next steps
- Standalone app sign-in — set up sign-in for a standalone app.
- Who can reach your Service — what your backend must check, with a Python example.
- Sign-in and users — app tokens in a Shell app.