Verifying tokens in your API
For backend and API developers. At the end of this page, your API verifies the TrustPin-Attestation header, logs the result, decides per endpoint what a request without a valid token may do, and can require an assertion for a sensitive operation. You will have tested it with a token from your app.
Requests from attested apps carry one header:
TrustPin-Attestation: <token>The token is a JWT signed by your verifier with ES256. Your API verifies it like any other JWT from a trusted issuer, then applies the attestation claims. To check tokens at nginx, Envoy, Kong, Cloudflare or AWS API Gateway instead, see Checking tokens at the gateway.
Before you start
- A verifier serving your published policy. See Deploying the verifier.
- Four values, shown with your project’s values filled in on the project’s Attestation page, Go-live guide tab, Step by step, step Verify tokens in your backend. With several environments, pick one in Environment first.
| Value in the console | What it is | Default |
|---|---|---|
| Issuer (iss) | The verifier’s TRUSTPIN_TOKEN_ISSUER. The deployment bundle sets it to the environment’s public URL from the Deployment tab | tprn::attest::<organization id>::<project id> when no URL is set |
| Audience (aud) | The verifier’s TRUSTPIN_TOKEN_AUDIENCE | tprn::project::<organization id>::<project id> |
| Project (tp.prj) | Your project, carried by every token whatever the audience | tprn::project::<organization id>::<project id> |
| JWKS URL | The verifier’s public signing keys | <verifier URL>/.well-known/jwks.json |
For assertions only, the API also needs the verifier’s URL: the environment’s URL on the Deployment tab, for example https://attest.example.com. The samples below read it from TRUSTPIN_VERIFIER_URL.
Check that your API’s network can reach the keys:
curl -s https://attest.example.com/.well-known/jwks.json
# {"keys":[{"kty":"EC","crv":"P-256","kid":"…","x":"…","y":"…", …}]}How your API and the verifier work together
Your API doesn’t call the verifier for an ordinary request: it verifies each token locally, with the verifier’s public keys. It calls the verifier only to fetch those keys, and to check an assertion on a sensitive operation.
Token format
Header: alg: ES256, typ: trustpin-attest+jwt, kid naming one of the verifier’s signing keys.
{
"iss": "<TRUSTPIN_TOKEN_ISSUER>",
"aud": "<TRUSTPIN_TOKEN_AUDIENCE>",
"sub": "<device key id>",
"iat": 1792400000,
"exp": 1792403600,
"jti": "<random>",
"bind": "<base64url(SHA-256(bound value))>",
"tp": {
"prj": "tprn::project::<organization id>::<project id>",
"plat": "apple",
"app": "ABCDE12345.com.example.app",
"ev": ["app_attest"],
"env": "production",
"pv": 7,
"mode": "enforce",
"result": "pass",
"reasons": []
}
}| Claim | Meaning |
|---|---|
iss | The verifier’s issuer: Issuer (iss) above |
aud | The audience: Audience (aud) above |
sub | The device key. It changes whenever the device attests a new key (reinstall, key-certificate expiry, rejected key, reset), so it is not a stable device or installation identifier |
iat, exp, jti | Issue and expiry times, and a random ID |
bind | Present only when the app bound the token: base64url(SHA-256(<bound value>)), unpadded. See Binding |
cnf | The device public key, used by POST /v1/assertion. Ignore it |
tp.prj | The project, tprn::project::<organization id>::<project id> |
tp.plat | apple, android, or debug for debug tokens |
tp.app | <teamId>.<bundleId> on Apple, the package name on Android |
tp.ev | An array of the evidence that was verified: app_attest, key_attestation, play_integrity, debug_token |
tp.env | production, development (Xcode-run builds, when the policy allows them) or debug (debug tokens) |
tp.pv | Policy version the decision was made under |
tp.mode, tp.result, tp.reasons | The policy outcome; see Monitor and enforce. Reason codes are listed in the verifier API reference |
Verification steps
- Fetch and cache
GET <verifier>/.well-known/jwks.json. Refetch when a token carries an unknownkid, at most once every 30 s, with a 5 s fetch timeout. - Reject any
algother thanES256and anytypother thantrustpin-attest+jwt. The type check also rejects key certificates, which the same keys sign. - Check the signature against the JWKS key named by
kid. - Check
iss,audandexp, allowing at most 60 seconds of clock skew, and thattp.prjequals your project. Refuse a token withouttp.prj. - If you use binding: compare
bindwith your own digest of the bound value (see Binding). With Require token binding on, also refuse a token withoutbind. - Reject
tp.env == "debug"outside development and staging. - Apply the mode rules below.
Gateways that locate keys through OIDC discovery can use <verifier>/.well-known/openid-configuration when the issuer is the verifier’s public https:// URL. Built-in JWT authorizers can’t check typ, tp.prj, debug tokens or binding; see Checking tokens at the gateway.
Binding
Binding ties a token to the user’s session, so a token copied from one session is refused with another. The app chooses the value:
- With
bindToHeader("Authorization")in the SDK, the value is that request’sAuthorizationheader, for exampleBearer eyJ…. Hash the header value exactly as received, scheme included. - With
setTokenBinding(value), the value is whatever the app passed, for example your session ID. Hash the same value on the server.
Agree on the value with the app developers. The Deployment tab’s Header the apps bind tokens to only records it for the Go-live guide snippets; the app sets binding in code. The example below hashes the value you pass as its second argument.
Monitor and enforce
| Policy mode | What the token says | What your API should do |
|---|---|---|
| Monitor | tp.result may be fail, with tp.reasons listing the policy checks that failed | Log the result and reasons, and allow the request. Use this phase to size the impact before switching to enforce |
| Enforce | New tokens always carry tp.result pass; a failing device gets no token. Tokens issued before the switch still say tp.mode monitor and tp.result fail until they expire, up to one Access token lifetime, and the verifier can’t recall them | Reject requests without a valid token on the endpoints you protect. For an immediate cut-off, also reject tp.result == "fail" |
tp.result fail only ever appears on a token issued in monitor mode, so decide from tp.result and your API’s own switch, not from tp.mode. Forged evidence never yields a token, and an app the policy doesn’t list gets 403 app_not_allowed in both modes.
Requests without the header
The SDKs never block the app’s own requests, so a request without the header is your decision, per endpoint. These requests come from old app versions, unsupported devices, attestation failures, and requests still waiting on a token. Common choices are to refuse sensitive operations, rate-limit harder, or flag the session.
Together, the decision for one request to a protected endpoint:
Example (Node.js, jose)
This is the verifier’s tested example, on jose 6.x (tested with 6.2.13), with one addition: an allowDebug option for staging APIs. Save it as verify.mjs and run npm install jose@6:
import { createHash } from "node:crypto";
import { createRemoteJWKSet, jwtVerify } from "jose";
// project: the expected tp.prj (tprn::project::<organizationId>::<projectId>);
// omitted, it is the audience when the audience has that form (the default),
// otherwise there is no project check.
// requireBind: refuse tokens without `bind` (policy tokens.binding: required).
// allowDebug: accept debug tokens (tp.env "debug"); staging APIs only.
export function makeVerifier({ jwksUrl, issuer, audience, project, requireBind = false, allowDebug = false }) {
const expectedProject = project || (audience.startsWith("tprn::project::") ? audience : "");
// Caches the keys for 5 minutes and refetches on an unknown kid at most
// once per 30 s (an unknown kid inside the cooldown is refused without a
// fetch); concurrent misses share one fetch, which gives up after 5 s.
const jwks = createRemoteJWKSet(new URL(jwksUrl), {
cacheMaxAge: 300_000,
cooldownDuration: 30_000,
timeoutDuration: 5_000,
});
return async function verify(token, authorization) {
const { payload } = await jwtVerify(token, jwks, {
algorithms: ["ES256"],
typ: "trustpin-attest+jwt",
issuer,
audience,
clockTolerance: 60,
requiredClaims: ["exp"],
});
if (expectedProject && payload.tp?.prj !== expectedProject) throw new Error("wrong project");
if (payload.tp?.env === "debug" && !allowDebug) throw new Error("debug token");
if (payload.bind === undefined && requireBind) throw new Error("unbound token");
if (payload.bind !== undefined) {
const expected = createHash("sha256").update(authorization).digest("base64url");
if (payload.bind !== expected) throw new Error("bound to another session");
}
return payload;
};
}verify(token, authorization) returns the claims, or throws on any failed check. Its second argument is the bound value: the Authorization header as received, or the value you agreed on with setTokenBinding.
To use it in an Express API, wrap it in a middleware that applies the rules above. Put the four values from the console in the API’s environment:
// attestation.mjs
import { makeVerifier } from "./verify.mjs";
const verify = makeVerifier({
jwksUrl: process.env.TRUSTPIN_JWKS_URL, // JWKS URL
issuer: process.env.TRUSTPIN_ISSUER, // Issuer (iss)
audience: process.env.TRUSTPIN_AUDIENCE, // Audience (aud)
project: process.env.TRUSTPIN_PROJECT, // Project (tp.prj); unset: taken from the audience
requireBind: process.env.TRUSTPIN_REQUIRE_BIND === "true", // Require token binding is on
allowDebug: process.env.TRUSTPIN_ALLOW_DEBUG === "true", // staging only: simulators and emulators
});
// Per endpoint: "enforce" refuses anything but a passing token; any other endpoint
// logs and allows (monitor). Example: TRUSTPIN_ENDPOINT_MODES='{"POST /transfer":"enforce"}'.
// Changing it needs no code change, only a restart: it is your fastest rollback.
const modes = JSON.parse(process.env.TRUSTPIN_ENDPOINT_MODES || "{}");
// app.post("/transfer", checkAttestation("POST /transfer"), transferHandler)
export function checkAttestation(endpoint) {
const mode = modes[endpoint] === "enforce" ? "enforce" : "monitor";
return async (req, res, next) => {
const token = req.get("TrustPin-Attestation");
let claims = null, outcome = "missing";
if (token) {
try {
claims = await verify(token, req.get("Authorization") ?? "");
outcome = claims.tp?.result === "pass" ? "pass" : "fail";
} catch (err) {
outcome = "invalid";
console.warn("attestation refused:", err.code ?? "", err.message);
}
}
const tp = claims?.tp ?? {};
console.info("attestation", JSON.stringify({
endpoint, outcome, reasons: tp.reasons, plat: tp.plat, app: tp.app, env: tp.env, ev: tp.ev,
mode: tp.mode, pv: tp.pv, bound: claims ? "bind" in claims : undefined,
appVersion: req.get("X-App-Version"), // whatever header your app sends its version in
}));
if (mode === "enforce" && outcome !== "pass") {
return res.status(401).json({ error: "attestation_required" });
}
req.attestation = claims; // null: no header, or a refused token
req.attestationMode = mode;
next();
};
}outcome is missing (no header), invalid (the token failed a verification step), pass or fail (tp.result). An endpoint not listed in TRUSTPIN_ENDPOINT_MODES is in monitor: every request goes through and is logged. An endpoint set to enforce refuses missing, invalid and fail. Rolling out uses this log line to measure, and this setting to enforce endpoint by endpoint.
These samples may be copied and modified freely, under the verifier licence’s Code Samples clause.
Test it end to end
-
Get a token from the app. Run a debug build that calls your API through the TrustPin SDK. On a real device, tokens carry
tp.envproduction, ordevelopmentfor an Xcode-run build when Accept development builds is on. Simulators and emulators need a debug token, whose tokens carrytp.envdebug: start a staging API withTRUSTPIN_ALLOW_DEBUG=trueto accept them. Never set it on a production API. -
Call a protected endpoint from the app. The API logs a line like this one:
attestation {"endpoint":"POST /transfer","outcome":"pass","reasons":[],"plat":"apple","app":"ABCDE12345.com.example.app","env":"development","ev":["app_attest"],"mode":"monitor","pv":3,"bound":true}Check that
appis your app, thatoutcomeispass(orfailwith thereasonsyou expect in monitor mode), and thatboundistrueif the app binds. -
Check the refusals with
curl. WithTRUSTPIN_ENDPOINT_MODES='{"POST /transfer":"enforce"}'on a test instance, both calls get401; in monitor they go through and the log says why:curl -i https://api.example.com/transfer -X POST # outcome missing curl -i https://api.example.com/transfer -X POST -H 'TrustPin-Attestation: not-a-token' # attestation refused: ERR_JWS_INVALID
If a token is refused, the attestation refused: log line names the check; see Troubleshooting. To read a token’s claims, decode its middle part:
node -e 'console.log(JSON.parse(Buffer.from(process.argv[1].split(".")[1], "base64url")))' "$TOKEN"Assertions for sensitive operations
A token stands for the device for its whole lifetime. For an operation your API must not accept on a reused token alone (a payment, a change of beneficiary), the app can send, next to the token, an assertion bound to that one operation. This needs SDK 7.1.0 or later and verifier 1.0.0 or later:
TrustPin-Attestation: <token>
TrustPin-Assertion: <base64url(clientData)>.<base64url(signature)>The app calls the SDK’s assertionHeaders with a SHA-256 digest of the operation (see the SDK pages, for example Swift). The client data names a single-use nonce the SDK fetched from your verifier, that digest (payload), and the token’s binding. Your API decides which endpoints require an assertion, and agrees with the app developers on what the digest covers, typically the raw request body.
To verify one, compute your own digest of the same bytes the app digested, base64url without padding (43 characters), and call the verifier:
POST <verifier>/v1/assertion
Content-Type: application/json
{ "token": "<TrustPin-Attestation value>", "assertion": "<TrustPin-Assertion value>", "payload": "<base64url(SHA-256 digest)>" }In Node.js, with the raw body bytes as received (for example from express.raw()), not a re-serialised copy:
// assertion.mjs
import { createHash } from "node:crypto";
// Returns the verifier's answer on 200, or null: the assertion was refused.
export async function verifyAssertion(req, rawBody) {
const res = await fetch(`${process.env.TRUSTPIN_VERIFIER_URL}/v1/assertion`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
token: req.get("TrustPin-Attestation"),
assertion: req.get("TrustPin-Assertion"),
payload: createHash("sha256").update(rawBody).digest("base64url"),
}),
signal: AbortSignal.timeout(5_000),
});
if (res.status !== 200) {
console.warn("assertion refused:", res.status, await res.text());
return null;
}
return res.json(); // { sub, bind?, tp, assertion: { payload } }
}A route that requires an assertion reads the raw body, runs checkAttestation, then checks the assertion before it parses the body:
import express from "express";
import { checkAttestation } from "./attestation.mjs";
import { verifyAssertion } from "./assertion.mjs";
const app = express();
app.post("/transfer",
express.raw({ type: "application/json" }), // req.body: the exact bytes the app digested
checkAttestation("POST /transfer"),
async (req, res) => {
const verified = await verifyAssertion(req, req.body);
if (!verified && req.attestationMode === "enforce") {
return res.status(403).json({ error: "assertion_required" });
}
const transfer = JSON.parse(req.body);
// … carry out the transfer
res.json({ ok: true });
});While the endpoint is in monitor, a refused assertion is logged and the operation goes ahead, like a refused token. Once the endpoint is in enforce, it is refused.
A 200 returns sub, bind when the token has one, tp, and assertion.payload, the digest the device signed. Any other answer means the assertion was refused:
| Answer | Meaning |
|---|---|
403 attestation_failed | The assertion failed, with assertion_invalid, payload_mismatch, key_mismatch or counter_invalid in reasons. payload_mismatch: your digest covers different bytes from the app’s |
401 invalid_token | The token wasn’t issued by this verifier, has expired, predates verifier 1.0.0, or names a platform, app or environment the current policy no longer allows |
401 invalid_challenge | The nonce is malformed, forged or expired (60 seconds by default) |
409 challenge_reused | The nonce was already used |
400 bad_request | A field is missing or malformed, for example a request without the TrustPin-Assertion header, or a payload that isn’t a base64url SHA-256 digest |
429, 503 | The verifier is rate-limiting or not ready. Refuse, and let the app retry |
The verifier checks the token’s signature, claims and project, and that the assertion carries the token’s binding. It doesn’t know your request, so keep running checkAttestation on the same request: it checks the binding against the request’s Authorization header, refuses debug tokens, and applies your mode rule to tp.result. The 200 answer carries tp.result too.
Troubleshooting
Symptom (attestation refused: log) | Likely cause | Fix |
|---|---|---|
ERR_JWT_CLAIM_VALIDATION_FAILED unexpected "iss" or "aud", or wrong project | The API expects a different issuer, audience or project from the verifier’s | Copy the values from the Go-live guide for the right environment. A verifier without a public URL uses the tprn::attest::… issuer |
ERR_JWKS_NO_MATCHING_KEY | The token was signed by another verifier, for example a staging app calling a production API | Point the app and the API at the same environment’s verifier |
ERR_JWKS_TIMEOUT or a fetch error | The API can’t reach the JWKS URL | Open the network path; check with curl from the API’s host |
ERR_JWT_EXPIRED | The token expired, or the clocks differ by more than 60 s | Synchronise the API’s and the verifier’s clocks with NTP |
bound to another session | The API hashes a different value from the one the app bound | Hash the header value exactly as received, scheme included, or the agreed setTokenBinding value |
unbound token | Require-binding is on and the app doesn’t bind | Bind in the app, or turn require-binding off in the API while Require token binding is off in the policy |
debug token | A simulator or emulator token reached an API without TRUSTPIN_ALLOW_DEBUG=true | Expected on production. On a staging API, set TRUSTPIN_ALLOW_DEBUG=true |
outcome missing, with no refused line | The request had no header | See Requests without the header and the SDK page’s troubleshooting |
For errors the app sees from the verifier, see the verifier API reference.
Next steps
- Rolling out: monitor to enforce: measure, switch the policy to enforce, and refuse endpoint by endpoint.
- Checking tokens at the gateway, if a gateway should check tokens instead of, or in front of, the API.