Groundfloor Docs

Who can reach your Service

Every Service is public. Decide who may use it, and check the signed-in user's token when it's the backend for a Shell or standalone app.

Every Service is on the public internet: anyone who knows its address can send it a request. Groundfloor delivers those requests to your container, but it doesn't sign anyone in or check who they are. Your Service decides who gets in.

Choose what your Service needs

Your Service is…ExampleWhat you do
Open to everyoneA website, blog, docs, public API or webhook receiverNothing. That's the default
An app with its own loginsWordPress, Ghost, Metabase, or your own app with user accountsNothing from Groundfloor: the app's own login protects it. Finish its installer as soon as it's deployed, and keep admin passwords strong
The backend for a Shell appAn API your Shell app calls with an app token from getAppToken(), or with the Shell site tokenCheck the token on every request, as below
The backend for a standalone app with sign-inAn API your app's front end calls after users sign in to the appCheck the app token on every request. See Check the token in a standalone app's backend

Signing in to your app doesn't protect your Service

Users sign in to your Shell site or your standalone app, not to the Services behind it. Anyone can call a Service's address directly, without signing in. If your Service is the backend for an app, it must check the token on every request itself.

Check the token in a Shell app's backend

Your Shell app sends the signed-in user's token as Authorization: Bearer <token> (see Secrets and backends). With Groundfloor sign-in, send an app token: a short-lived token for your app only, from getAppToken(). Your backend can then refuse tokens meant for any other app. The Shell site token still works too, until Groundfloor announces a date to retire it for backends. Either way the token is a JWT signed by your workspace's sign-in. Your backend checks it, then decides what the user may do.

Find your issuer and client ID

Ask Groundfloor for your Shell site's sign-in settings. No token is needed:

curl "https://platform.groundfloor.cloud/v1/public/workspaces/by-host?host=<workspace-slug>.app.groundfloor.cloud"

Use your own domain as host if your Shell site has one. Every environment's Shell site has the same issuer and client ID, so one lookup is enough. The answer looks like this:

{
  "workspace_id": "3f6c…",
  "mode": "groundfloor",
  "oidc": {
    "issuer": "https://auth.groundfloor.cloud/realms/gf-ws-3f6c…",
    "client_id": "shell"
  },
  "site_host": "<workspace-slug>.app.groundfloor.cloud"
}
  • Check that workspace_id is your workspace's ID, so you know you asked about the right site.
  • oidc.issuer is your issuer. With Groundfloor sign-in it's unique to your workspace; with External sign-in it's your identity provider's issuer.
  • oidc.client_id is your client ID: shell with Groundfloor sign-in, or the client ID you entered for External sign-in.
  • oidc is null when the sign-in mode is None: there are no tokens to check.
  • Where each environment has its own Shell site (rolling out), the answer also has environment_id and environment_label (dev, staging or prod), and site_host is that environment's site address.

Look these up once, when you set up the Service. Copy both values exactly as they appear, including any trailing / on the issuer, and give them to your Service as AUTH_ISSUER and AUTH_CLIENT_ID, for example as ENV lines in its Dockerfile. Neither is secret. Look them up again if you change your sign-in mode.

Never look them up at runtime from the request's Host header: whoever sends the request chooses that header, so they could point your Service at a site whose tokens they control.

Check an app token

Rolling out. Your Shell app gets the token with getAppToken() and sends it to your backend. An app token is for your backend only: Groundfloor's own APIs refuse it, so your app keeps sending the Shell site token to them.

Check it exactly like a standalone app's token, with two settings you give your Service yourself, since a Shell app's backend doesn't get the GROUNDFLOOR_AUTH_* variables:

SettingValue
Issueroidc.issuer from by-host, exactly as returned
Audienceapp-<app-id>, your app's ID from the Client Portal or gf apps ls

An app token has aud and azp equal to app-<app-id>, typ Bearer, the user's sub, email, roles and, with Multi-tenant on, organization. It lasts at most 5 minutes, and never longer than the user's Shell sign-in. Key records on sub, and read roles from the roles claim, ignoring offline_access, uma_authorization and names starting with default-roles-.

server.mjs
import { requireAppUser } from "@groundfloorcloud/app-auth";

app.use("/api", requireAppUser({
  issuer: process.env.AUTH_ISSUER, // exactly as by-host returned it
  audience: "app-<app-id>",        // your app's ID
}));
app.post("/api/refunds", requireAppUser({ issuer: process.env.AUTH_ISSUER, audience: "app-<app-id>", roles: ["admin"] }), createRefund);

In Python, use the standalone example with ISSUER and AUDIENCE set to these two values. A token minted for another app fails the audience check (wrong_audience), and so does a Shell site token.

A valid signature isn't enough

Groundfloor signs app tokens for many workspaces with the same key, which your workspace's key address lists. A token from another workspace or for another app can carry a valid signature. Always check iss, aud and azp, as the library and the Python example do.

Accept both while you move over

To keep accepting the Shell site token while your app moves to app tokens, try the app token first and fall back to the Shell site token only when the token isn't for your app:

import { AppAuthError, createAppTokenVerifier, createShellTokenVerifier } from "@groundfloorcloud/app-auth";

const asApp = createAppTokenVerifier({ issuer, audience: "app-<app-id>" });
const asShell = createShellTokenVerifier({ issuer });

async function verify(token) {
  try {
    return await asApp(token);
  } catch (err) {
    // A Shell site token has no app audience, so the app verifier refuses it.
    if (err instanceof AppAuthError && (err.code === "wrong_audience" || err.code === "wrong_client")) {
      return asShell(token);
    }
    throw err;
  }
}

Roles are in roles on an app token and in realm_access.roles on a Shell site token; the library's user.roles reads either.

What to check

These checks are for the Shell site token, and for your own provider's tokens with External sign-in. For an app token, see Check an app token. Reject the request with 401 unless all of these hold:

  • Signature: the token is signed with RS256 by one of the keys at {issuer}/protocol/openid-connect/certs. That address holds more than one key, so pick the one whose kid matches the token's header. With External sign-in, use your provider's key address instead (its jwks_uri).
  • Issuer: iss equals your issuer exactly.
  • Expiry: exp is in the future.
  • Client: the token was issued to your client ID.
    • With Groundfloor sign-in, azp equals your client ID (shell). A Shell site token has no audience for your app, so don't require aud to name it. To accept only tokens for your app, use app tokens instead.
    • With External sign-in, the token must name your client ID, either in azp (or your provider's equivalent, such as cid or appid) or in aud. Never accept a token that names it in neither.
  • A user's token: the token has no x-client-key or x-userid claim. Groundfloor's own Coderunner management and developer tokens carry an x-client-key or x-userid claim and are signed with a key your workspace's key address also lists, so the signature check alone doesn't stop them.

Then return 403 if the user is signed in but their role doesn't allow what they asked for.

With External sign-in, check whether your provider lets anyone sign up. If it does, "any signed-in user" means anyone at all, so check a role for everything that isn't public.

Read the user and their role

ClaimWhat it is
subThe user's ID, with Groundfloor and External sign-in. Store and match the user's records by it
realm_access.rolesThe user's roles: the built-in viewer, user and admin, and roles you created on App authentication → Roles. The list also holds roles your app can ignore, such as offline_access, uma_authorization and names starting with default-roles-
organizationThe user's companies (tenants), when Multi-tenant is on in App authentication

With External sign-in, roles come from your identity provider, in whatever claim it uses.

To tie records to a user, use sub from the verified token, never a user ID sent in the request. Don't use external_user_id for this. See Use sub as the user's ID.

With Multi-tenant on, roles don't separate companies

A role applies across every company: an admin in one company is an admin for your whole app. So filter every read and write by the user's organization claim as well as their role. The claim can hold more than one company, so check that the record's company is one of them. Each company is named by its tenant's alias (set when you create the tenant, made from its name by default) and may carry its ID. The examples below accept a list of aliases or an object keyed by alias. Turning Multi-tenant off removes the claim from app tokens.

Example: FastAPI

Uses PyJWT (pip install "pyjwt[crypto]" fastapi). PyJWKClient caches the keys and picks the one named by the token's kid. When a token names a kid it doesn't have, it fetches the keys again, every time; the timeout stops a slow fetch from holding up requests.

main.py
import os

import jwt
from fastapi import Depends, FastAPI, HTTPException
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer

ISSUER = os.environ["AUTH_ISSUER"]  # exactly as by-host returned it
CLIENT_ID = os.environ["AUTH_CLIENT_ID"]  # "shell" with Groundfloor sign-in
JWKS_URL = os.environ.get(
    "AUTH_JWKS_URL", ISSUER.rstrip("/") + "/protocol/openid-connect/certs"
)

jwks = jwt.PyJWKClient(JWKS_URL, timeout=5)
bearer = HTTPBearer(auto_error=False)

app = FastAPI()


def issued_to_us(claims: dict) -> bool:
    if CLIENT_ID in (claims.get("azp"), claims.get("cid"), claims.get("appid")):
        return True
    aud = claims.get("aud")  # External sign-in only; Groundfloor tokens use azp
    return aud == CLIENT_ID or (isinstance(aud, list) and CLIENT_ID in aud)


def current_user(creds: HTTPAuthorizationCredentials | None = Depends(bearer)) -> dict:
    unauthorized = HTTPException(401, "Sign in first", headers={"WWW-Authenticate": "Bearer"})
    if creds is None:
        raise unauthorized
    try:
        key = jwks.get_signing_key_from_jwt(creds.credentials)
        claims = jwt.decode(
            creds.credentials,
            key.key,
            algorithms=["RS256"],
            issuer=ISSUER,
            options={"require": ["exp", "iss"], "verify_aud": False},
            leeway=30,
        )
    except jwt.PyJWKClientConnectionError:
        raise HTTPException(503, "Can't reach the sign-in service")
    except jwt.PyJWTError:
        raise unauthorized
    if not issued_to_us(claims):
        raise unauthorized
    if "x-client-key" in claims or "x-userid" in claims:
        raise unauthorized  # a Groundfloor management token, not a user's
    return claims


def user_roles(claims: dict) -> set[str]:
    access = claims.get("realm_access")
    roles = access.get("roles") if isinstance(access, dict) else None
    return {r for r in roles if isinstance(r, str)} if isinstance(roles, list) else set()


def user_companies(claims: dict) -> set[str]:
    org = claims.get("organization")
    if isinstance(org, dict):
        return {k for k in org if isinstance(k, str)}
    if isinstance(org, list):
        return {o for o in org if isinstance(o, str)}
    return set()


def require_role(*roles: str):
    def check(claims: dict = Depends(current_user)) -> dict:
        if user_roles(claims).isdisjoint(roles):
            raise HTTPException(403, "You don't have access to this")
        return claims

    return check


@app.get("/api/orders")
def list_orders(claims: dict = Depends(require_role("user", "admin"))):
    user_id = claims["sub"]  # store and match this user's records by sub
    companies = user_companies(claims)  # Multi-tenant: only this user's companies
    return {"orders": [], "user_id": user_id, "companies": sorted(companies)}


@app.post("/api/refunds")
def create_refund(claims: dict = Depends(require_role("admin"))):
    return {"ok": True}  # admins only

verify_aud is off because Groundfloor tokens can carry an aud that isn't yours, and PyJWT rejects any aud it wasn't told to expect; issued_to_us checks the client instead. Set AUTH_JWKS_URL only with External sign-in. A malformed realm_access or organization claim counts as no roles and no companies, so the request gets 403, not an error.

Example: Node.js

Uses jose (npm install jose), as Express middleware. createRemoteJWKSet caches the keys and picks the one named by the token's kid. It fetches the keys again for an unknown kid at most every 30 seconds, and gives up on a fetch after 5 seconds.

auth.mjs
import { createRemoteJWKSet, jwtVerify } from "jose";

const ISSUER = process.env.AUTH_ISSUER; // exactly as by-host returned it
const CLIENT_ID = process.env.AUTH_CLIENT_ID; // "shell" with Groundfloor sign-in
if (!ISSUER || !CLIENT_ID) throw new Error("Set AUTH_ISSUER and AUTH_CLIENT_ID");
const JWKS = createRemoteJWKSet(
  new URL(process.env.AUTH_JWKS_URL ?? `${ISSUER.replace(/\/$/, "")}/protocol/openid-connect/certs`),
);

function issuedToUs(p) {
  if ([p.azp, p.cid, p.appid].includes(CLIENT_ID)) return true;
  return Array.isArray(p.aud) ? p.aud.includes(CLIENT_ID) : p.aud === CLIENT_ID; // External only
}

// req.user holds the token's claims, or the request ends with 401.
// req.user.sub is the user's ID: store and match their records by it.
export async function requireUser(req, res, next) {
  const [scheme, token] = (req.headers.authorization ?? "").split(" ");
  if (scheme?.toLowerCase() !== "bearer" || !token) return res.status(401).end();
  try {
    const { payload } = await jwtVerify(token, JWKS, {
      issuer: ISSUER,
      algorithms: ["RS256"],
      requiredClaims: ["exp"],
      clockTolerance: 30,
    });
    if (!issuedToUs(payload)) return res.status(401).end();
    if ("x-client-key" in payload || "x-userid" in payload) return res.status(401).end(); // not a user's token
    req.user = payload;
    next();
  } catch {
    res.status(401).end();
  }
}

export function requireRole(...roles) {
  return (req, res, next) => {
    const r = req.user?.realm_access?.roles;
    const userRoles = Array.isArray(r) ? r : [];
    if (!roles.some((role) => userRoles.includes(role))) return res.status(403).end();
    next();
  };
}

// Multi-tenant: the companies whose records this user may see.
export function userCompanies(user) {
  const org = user?.organization;
  if (Array.isArray(org)) return org.filter((o) => typeof o === "string");
  if (org && typeof org === "object") return Object.keys(org);
  return [];
}
app.get("/api/orders", requireUser, requireRole("user", "admin"), listOrders);
app.post("/api/refunds", requireUser, requireRole("admin"), createRefund);

Allow calls from your Shell site

Your Shell site and your Service are on different addresses, so the browser asks the Service first (a CORS preflight) before sending a request with an Authorization header. Unless the Service answers it, the browser blocks the call. Allow your Shell site's address, and your own domain if it has one. Each environment has its own Shell site (rolling out), so also allow the dev and staging sites whose apps call this Service:

main.py
from fastapi.middleware.cors import CORSMiddleware

app.add_middleware(
    CORSMiddleware,
    allow_origins=[
        "https://<workspace-slug>.app.groundfloor.cloud",          # prod
        "https://<workspace-slug>.staging.app.groundfloor.cloud",  # staging
        "https://<workspace-slug>.dev.app.groundfloor.cloud",      # dev
    ],
    allow_methods=["GET", "POST", "PUT", "PATCH", "DELETE"],
    allow_headers=["Authorization", "Content-Type"],
)

In Node.js, use the cors package with the same settings. Don't use a bare cors(), which allows every origin:

import cors from "cors";

app.use(cors({
  origin: [
    "https://<workspace-slug>.app.groundfloor.cloud",
    "https://<workspace-slug>.staging.app.groundfloor.cloud",
    "https://<workspace-slug>.dev.app.groundfloor.cloud",
  ],
  allowedHeaders: ["Authorization", "Content-Type"],
}));

The middleware answers the preflight before your token check runs, so preflights don't get 401. The token travels in a header, not a cookie, so you don't need to allow credentials. Never combine * as the allowed origin with credentials.

Check the token in a standalone app's backend

A standalone app with sign-in has its own sign-in client, app-<app-id>. Its users' tokens name that client, so your backend can accept tokens for this app and refuse all others: other apps' tokens, Shell site tokens and anything else signed by your workspace's sign-in.

Get the settings

When you deploy the app's main Service, Groundfloor sets these variables on the running Service, unless you set them yourself. None is secret. They're the backend's runtime environment, not variables in your front end's build.

VariableValue
GROUNDFLOOR_AUTH_ISSUERThe issuer of your app's tokens
GROUNDFLOOR_AUTH_JWKS_URLWhere the signing keys are: {issuer}/protocol/openid-connect/certs
GROUNDFLOOR_AUTH_AUDIENCEapp-<app-id>
GROUNDFLOOR_AUTH_CLIENT_IDapp-<app-id>, for the front end's sign-in
GROUNDFLOOR_APP_IDThe app's ID

They're set only while app sign-in is switched on and the workspace uses Groundfloor sign-in. For any other backend, copy the values from the app's Authentication card or gf apps auth <app> --json (issuer, jwks_url, client_id).

What to check

Reject the request with 401 unless all of these hold:

  • Signature: the token is signed with RS256 by the key at the JWKS URL whose kid matches the token's header. Refuse every other algorithm.
  • Issuer: iss equals the issuer exactly.
  • Audience: aud contains app-<app-id>. It can hold other values too, such as account.
  • Client: azp equals app-<app-id>. Refuse a token without azp.
  • A user's token: there's no x-client-key or x-userid claim. Groundfloor's own Coderunner management and developer tokens carry an x-client-key or x-userid claim and are signed with a key your workspace's key address also lists, so the signature check alone doesn't stop them.
  • Expiry: exp is present and in the future. Allow 30 seconds of clock difference; never more than 60.
  • Type: typ, when present, is Bearer, so ID and refresh tokens are refused.
  • User: sub is present.

Then:

  • Use sub as the user's ID. Store and match their records by it, never by a user ID or email sent in the request. See Use sub as the user's ID.
  • Check roles. Any user of the workspace can sign in to any of its apps, so a valid token only proves who the user is. The user's roles are in the roles claim (and in realm_access.roles). Ignore offline_access, uma_authorization and names starting with default-roles-, treat a malformed claim as no roles, and return 403 when the role a route needs is missing.
  • With Multi-tenant on, also filter every read and write by the organization claim, which holds the user's tenants' aliases and may carry their IDs. See the callout above. With Multi-tenant off, app tokens have no organization claim.

Example: Node.js with the app sign-in library

The app sign-in library reads the variables above and makes every check:

server.mjs
import express from "express";
import { requireAppUser } from "@groundfloorcloud/app-auth";

const app = express();

// Every /api route needs a signed-in user of this app (401 otherwise).
app.use("/api", requireAppUser());

// This one also needs the "editor" role (403 otherwise).
app.post("/api/posts", requireAppUser({ roles: ["editor"] }), (req, res) => {
  const user = res.locals.appUser; // { sub, roles, organization, email, ... }
  res.json({ owner: user.sub }); // store and match records by sub
});

To check a token yourself, call verifyAppToken(token). It returns the user or throws an AppAuthError with the status to answer.

Example: Python

Uses PyJWT (pip install "pyjwt[crypto]", version 2.8 or later):

app_auth.py
import os

import jwt
from jwt import PyJWKClient

ISSUER = os.environ["GROUNDFLOOR_AUTH_ISSUER"]  # fail at startup if unset
AUDIENCE = os.environ["GROUNDFLOOR_AUTH_AUDIENCE"]  # app-<app-id>
JWKS_URL = os.environ.get(
    "GROUNDFLOOR_AUTH_JWKS_URL", ISSUER.rstrip("/") + "/protocol/openid-connect/certs"
)
IGNORED = {"offline_access", "uma_authorization"}

# Caches the keys; fetches them again for an unknown kid, so keep the timeout short.
jwks = PyJWKClient(JWKS_URL, cache_keys=True, lifespan=600, timeout=5)


def verify_app_token(token: str) -> dict:
    """Return the claims, or raise jwt.InvalidTokenError (answer 401)."""
    if jwt.get_unverified_header(token).get("alg") != "RS256":
        raise jwt.InvalidAlgorithmError("RS256 only")
    key = jwks.get_signing_key_from_jwt(token)
    claims = jwt.decode(
        token,
        key.key,
        algorithms=["RS256"],
        issuer=ISSUER,  # exact match
        audience=AUDIENCE,  # aud must contain app-<app-id>
        leeway=30,  # seconds; never more than 60
        options={"require": ["exp", "iss", "aud", "sub"]},
    )
    if claims.get("azp") != AUDIENCE:  # always set; a token without it is refused
        raise jwt.InvalidTokenError("issued to another client")
    if "x-client-key" in claims or "x-userid" in claims:
        raise jwt.InvalidTokenError("not an end-user token")  # Groundfloor management token
    if "typ" in claims and claims["typ"] != "Bearer":
        raise jwt.InvalidTokenError("not an access token")
    if not isinstance(claims.get("sub"), str) or not claims["sub"]:
        raise jwt.InvalidTokenError("no subject")
    return claims


def roles_of(claims: dict) -> set[str]:
    raw = claims.get("roles")
    if not isinstance(raw, list):
        realm = claims.get("realm_access")
        raw = realm.get("roles") if isinstance(realm, dict) else None
    if not isinstance(raw, list):
        return set()  # malformed = no roles = 403, never 500
    return {
        r for r in raw
        if isinstance(r, str) and r not in IGNORED and not r.startswith("default-roles-")
    }

Use it in a FastAPI dependency like current_user above: answer 401 when verify_app_token raises, 503 on jwt.PyJWKClientConnectionError, and 403 when roles_of(claims) lacks the role a route needs. Key records on claims["sub"].

Allow calls from your app

If your front end and your backend are on different addresses, allow the front end's address with CORS, as in Allow calls from your Shell site. If the backend is the app's main Service and serves the front end itself, there's nothing to allow.

Every app on your Shell site can use the user's token

Only install apps you trust

Every app on your Shell site, including apps you didn't write, runs in the same browser window. It can get the signed-in user's Shell site token, use it to get app tokens for any app that user can open, and call your backends as that user. Only install apps you trust, and check roles for anything sensitive.

App tokens don't keep apps on one Shell site apart in the browser. What they do:

  • A backend that checks app tokens refuses tokens minted for other apps, and the Shell site token.
  • An app token works only on your backend, not on Groundfloor's APIs or another app's backend. So a token that leaks from your backend, for example into a log, can't be used anywhere else.

A Shell site token, by contrast, is accepted by every backend in the workspace that checks Shell site tokens. A standalone app has its own sign-in, so it isn't affected.

For Node.js, the app sign-in library checks Shell site tokens too: verifyShellToken(token, { issuer }), or requireAppUser({ shell: true, issuer }) as middleware.

Next steps

On this page