Authentication
Identity tokens
Bind devices and profiles to the logged-in person with a short-lived token your backend signs.
The app key ships inside your app and web pages, so anyone can read it. With the key alone, someone could register their own phone for another person's id and receive that person's pushes. An identity token closes that. Your backend knows who is logged in. It signs a short-lived token that names that person. The app hands it to the Sapagan SDK. Sapagan then registers devices and writes profiles only for the person the token names.
The token goes in the X-Sapagan-User-Token header.
Two ways to sign#
- An identity key (HMAC). An owner creates one in the console (Settings, Setup, App identity). The page shows the key id (
kid, 16 hex characters) and the secret (sapagan_isk_and 64 hex characters) once. Keep the secret in your backend's secret store. - Your registered session issuer. A workspace whose sessions are already registered with Sapagan may send the person's own session JWT. It is verified against that issuer, and its
subis the external id. There is nothing to mint.
The token#
A compact JWT signed with HS256:
| Part | Value |
|---|---|
header alg | HS256. The only algorithm accepted. |
header typ | sapagan-id+jwt, exactly. |
header kid | The identity key's id. |
sub | The person's external id, 1 to 200 characters. |
aud | sapagan:<workspace id>, exactly one value. Shown at Settings, Setup, "For your developer". |
iat | Issued at, in seconds. |
exp | Expiry, in seconds. exp - iat is at most 3600. Use 600. |
| signing key | The UTF-8 bytes of the whole secret string, sapagan_isk_ included. |
Sapagan allows 60 seconds of clock skew either way. A token is not single use: the SDK sends the same token with retries. Keep it short, send it only over HTTPS and never log it.
Test vector#
Workspace 0190a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a5b, kid 0123456789abcdef, secret sapagan_isk_00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff, sub user-42, iat 1800000000 and exp 1800000600 give exactly this token (header and payload JSON with keys in the order above and no spaces):
eyJhbGciOiJIUzI1NiIsInR5cCI6InNhcGFnYW4taWQrand0Iiwia2lkIjoiMDEyMzQ1Njc4OWFiY2RlZiJ9.eyJzdWIiOiJ1c2VyLTQyIiwiYXVkIjoic2FwYWdhbjowMTkwYTFiMi1jM2Q0LTdlNWYtOGE5Yi0wYzFkMmUzZjRhNWIiLCJpYXQiOjE4MDAwMDAwMDAsImV4cCI6MTgwMDAwMDYwMH0.loDUwcK35O0K5b2BLlf_Q5znXX3m3-SGoKhNgVXwSlUSigning in your backend#
import { createHmac } from "node:crypto";
const b64url = (s) => Buffer.from(s).toString("base64url");
export function sapaganIdentityToken({ workspaceId, kid, secret, subject, ttlSeconds = 600 }) {
const iat = Math.floor(Date.now() / 1000);
const header = b64url(JSON.stringify({ alg: "HS256", typ: "sapagan-id+jwt", kid }));
const payload = b64url(JSON.stringify({ sub: subject, aud: `sapagan:${workspaceId}`, iat, exp: iat + ttlSeconds }));
const sig = createHmac("sha256", Buffer.from(secret, "utf8")).update(`${header}.${payload}`).digest("base64url");
return `${header}.${payload}.${sig}`;
}import base64, hashlib, hmac, json, time
def b64url(b: bytes) -> str:
return base64.urlsafe_b64encode(b).rstrip(b"=").decode()
def sapagan_identity_token(workspace_id, kid, secret, subject, ttl=600):
iat = int(time.time())
header = b64url(json.dumps({"alg": "HS256", "typ": "sapagan-id+jwt", "kid": kid}, separators=(",", ":")).encode())
payload = b64url(json.dumps({"sub": subject, "aud": f"sapagan:{workspace_id}", "iat": iat, "exp": iat + ttl}, separators=(",", ":")).encode())
sig = hmac.new(secret.encode(), f"{header}.{payload}".encode(), hashlib.sha256).digest()
return f"{header}.{payload}.{b64url(sig)}"Serve the token only to the logged-in person themselves: an authenticated route that answers their own token, never one for an id the client names.
Wiring the SDKs#
- Flutter:
SapaganConfig(userTokenProvider: ...). See Flutter. - Web:
createSapagan({ getUserToken }). See Web. Browsers also need the page's origin under Web origins.
What the API does with it#
On POST /v1/batch:
- App keys always need a token for profile items, device registrations and relationships.
- Track keys need it when the workspace has "Identity required" on (Settings, Setup). New production workspaces start with it on.
- A token that is sent always binds, whatever the setting.
- Bound items must name the token's
sub. A bound profile may link onlyanonymous_ididentifiers and may not setemailorphone. - Refusals are per item:
user_token_required,user_token_mismatch,identifier_not_allowed,identity_alias. - A token that does not verify is
401 invalid_user_tokenfor the whole request, before anything is written. - Events and device deletions are not bound. A workspace (server) key is never bound.
GET /v1/inapp/messages accepts identity tokens as well as sessions, and needs one in a production workspace.
Rotating a key#
At most two identity keys are active, so rotation never breaks running apps.
- Create a new key in Setup.
- Deploy your backend with the new
kidand secret. Apps need no change. - When tokens signed with the old key have expired (at most an hour), retire it. Tokens signed with a retired key are refused at once.
For a leaked secret: create a new key, switch your backend and retire the leaked key immediately. Each change is audited with the key id, never the secret.