Receiving an application in the page, and verifying its token
The popup hands your page the application as JSON with a signed token. Your server verifies the token before trusting any of it, in Node, Python or PHP.
12 minute read
Never trust the application your page holds. The page is a browser: anyone can call your onApplied with JSON they wrote. Trust only what your server reads out of the token after verifying it. This page shows how.
What the page receives
After Apply, the popup posts one message to the page that opened it, and only to that page's origin, the one checked against your sites:
| Message | When |
|---|---|
{ type: 'certo.application', application, token, application_id, state } | Delivery to the page is on |
{ type: 'certo.application.submitted', application_id, state } | Delivery to your server only: no content reaches the browser |
{ type: 'certo.cancel' } | The candidate closed the popup |
v1.js listens for it, checks it came from https://certo.bio, and calls onApplied(result), onSubmitted({ applicationId, state }) or onCancel(detail), and dispatches certo:applied, certo:submitted or certo:cancel on the button. If you open the popup without v1.js, accept a message only when event.origin === 'https://certo.bio' and its type is one of the three.
Then send the token to your server:
onApplied(result) {
fetch('/certo/applied', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ token: result.token }),
})
}
The token
A compact JWS signed with ES256 by certo's apply key (its own key, never the one that signs certificates).
| Part | What |
|---|---|
header alg, kid | ES256, and which of certo's keys signed it |
iss | https://certo.bio |
aud | The id the button opened with: your ao_, a position's ap_ or the session's as_ |
sub | The application's id |
nonce | Your state, from the button or the apply session |
iat, exp | When it was signed, and ten minutes later |
jti | The token's own id: use it once |
application | The application, below |
The keys: https://certo.bio/.well-known/certo-apply-jwks.json. Cache them for a few minutes and fetch again when a token names a kid you have not seen.
Your server checks, in this order: the signature against the key its kid names, iss, aud is one of your ids, nonce equals the state you kept for this visitor, exp has not passed, and jti was never used before. Only then is application yours to use. Each sample below answers ok with the application, or the first check that failed: malformed, alg, kid, signature, iss, aud, nonce, exp or replay.
Node
Node 18 or later, no dependencies. Save it as certo-apply-token.mjs:
// Verify an Apply with certo token on your server. Node 18 or later, no dependencies.
import { webcrypto } from 'node:crypto'
import { Buffer } from 'node:buffer'
export const ISSUER = 'https://certo.bio'
export const JWKS_URL = 'https://certo.bio/.well-known/certo-apply-jwks.json'
// The public keys, fetched again after five minutes or when a token names a key not seen yet.
let cached = { at: 0, jwks: { keys: [] } }
export async function loadJwks(kid, now = Date.now()) {
const known = cached.jwks.keys.some((k) => k.kid === kid)
if (!known || now - cached.at > 300_000) {
const res = await fetch(JWKS_URL)
if (!res.ok) throw new Error(`JWKS answered ${res.status}`)
cached = { at: now, jwks: await res.json() }
}
return cached.jwks
}
// Each token is used once. Keep the ids where every server of yours sees them (a database
// table or Redis, with the token's exp as the expiry); this one is for a single process.
const used = new Map()
export async function useJtiOnce(jti, exp) {
const now = Math.floor(Date.now() / 1000)
for (const [id, until] of used) if (until < now) used.delete(id)
if (used.has(jti)) return false
used.set(jti, exp)
return true
}
const json = (part) => JSON.parse(Buffer.from(part, 'base64url').toString('utf8'))
/**
* token the `token` your page received from the popup
* jwks the key set, or loadJwks (called with the token's kid)
* audience the button's id (ao_..., ap_... or as_...), or a list of your ids
* nonce the state you put on the button or in the apply session, kept on your server
* Answers { ok: true, application, claims } or { ok: false, reason }.
*/
export async function verifyApplicationToken(token, { jwks, audience, nonce, now = Math.floor(Date.now() / 1000), useJti = useJtiOnce }) {
const parts = typeof token === 'string' ? token.split('.') : []
if (parts.length !== 3) return { ok: false, reason: 'malformed' }
let header, claims
try {
header = json(parts[0])
claims = json(parts[1])
} catch {
return { ok: false, reason: 'malformed' }
}
if (!header || typeof header !== 'object' || !claims || typeof claims !== 'object') return { ok: false, reason: 'malformed' }
if (header.alg !== 'ES256') return { ok: false, reason: 'alg' }
const keys = typeof jwks === 'function' ? await jwks(header.kid) : jwks
const jwk = keys.keys.find((k) => k.kid === header.kid)
if (!jwk) return { ok: false, reason: 'kid' }
const key = await webcrypto.subtle.importKey('jwk', { kty: jwk.kty, crv: jwk.crv, x: jwk.x, y: jwk.y }, { name: 'ECDSA', namedCurve: 'P-256' }, false, ['verify'])
const signature = Buffer.from(parts[2], 'base64url')
const signed = Buffer.from(`${parts[0]}.${parts[1]}`)
if (signature.length !== 64 || !(await webcrypto.subtle.verify({ name: 'ECDSA', hash: 'SHA-256' }, key, signature, signed))) {
return { ok: false, reason: 'signature' }
}
if (claims.iss !== ISSUER) return { ok: false, reason: 'iss' }
if (!(Array.isArray(audience) ? audience : [audience]).includes(claims.aud)) return { ok: false, reason: 'aud' }
if (!nonce || claims.nonce !== nonce) return { ok: false, reason: 'nonce' }
if (typeof claims.exp !== 'number' || claims.exp < now) return { ok: false, reason: 'exp' }
if (typeof claims.jti !== 'string' || !(await useJti(claims.jti, claims.exp))) return { ok: false, reason: 'replay' }
return { ok: true, application: claims.application, claims }
}
Then, in your endpoint:
import { loadJwks, verifyApplicationToken } from './certo-apply-token.mjs'
app.post('/certo/applied', express.json(), async (req, res) => {
const { state, audience } = req.session.certo ?? {}
const result = await verifyApplicationToken(String(req.body.token ?? ''), { jwks: loadJwks, audience, nonce: state })
if (!result.ok) return res.status(400).json({ refused: result.reason })
await saveApplication(result.application)
res.status(204).end()
})
For recipes a and c, audience is the id on your button, or the list of your ids; for an apply session, the session's as_ id you kept.
Python
Python 3.9 or later with the cryptography package:
# Verify an Apply with certo token on your server. Python 3.9 or later; pip install cryptography.
import base64
import json
import time
import urllib.request
from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives.asymmetric.utils import encode_dss_signature
ISSUER = "https://certo.bio"
JWKS_URL = "https://certo.bio/.well-known/certo-apply-jwks.json"
_cache = {"at": 0.0, "jwks": {"keys": []}}
def load_jwks(kid):
"""The public keys, fetched again after five minutes or when a token names a key not seen yet."""
known = any(k.get("kid") == kid for k in _cache["jwks"]["keys"])
if not known or time.time() - _cache["at"] > 300:
with urllib.request.urlopen(JWKS_URL, timeout=10) as res:
_cache["jwks"] = json.load(res)
_cache["at"] = time.time()
return _cache["jwks"]
# Each token is used once. Keep the ids where every server of yours sees them (a database
# table or Redis, with the token's exp as the expiry); this one is for a single process.
_used = {}
def use_jti_once(jti, exp):
now = int(time.time())
for old in [j for j, until in _used.items() if until < now]:
del _used[old]
if jti in _used:
return False
_used[jti] = exp
return True
def _b64(part):
return base64.urlsafe_b64decode(part + "=" * (-len(part) % 4))
def verify_application_token(token, jwks, audience, nonce, now=None, use_jti=use_jti_once):
"""jwks: the key set, or load_jwks (called with the token's kid);
audience: the button's id (ao_..., ap_... or as_...) or a list of your ids;
nonce: the state you put on the button or in the apply session, kept on your server.
Answers {"ok": True, "application": ..., "claims": ...} or {"ok": False, "reason": ...}."""
now = int(time.time()) if now is None else now
parts = token.split(".") if isinstance(token, str) else []
if len(parts) != 3:
return {"ok": False, "reason": "malformed"}
try:
header = json.loads(_b64(parts[0]))
claims = json.loads(_b64(parts[1]))
signature = _b64(parts[2])
except ValueError:
return {"ok": False, "reason": "malformed"}
if not isinstance(header, dict) or not isinstance(claims, dict):
return {"ok": False, "reason": "malformed"}
if header.get("alg") != "ES256":
return {"ok": False, "reason": "alg"}
key_set = jwks(header.get("kid")) if callable(jwks) else jwks
jwk = next((k for k in key_set.get("keys", []) if k.get("kid") == header.get("kid")), None)
if jwk is None:
return {"ok": False, "reason": "kid"}
key = ec.EllipticCurvePublicNumbers(
int.from_bytes(_b64(jwk["x"]), "big"), int.from_bytes(_b64(jwk["y"]), "big"), ec.SECP256R1()
).public_key()
if len(signature) != 64:
return {"ok": False, "reason": "signature"}
der = encode_dss_signature(int.from_bytes(signature[:32], "big"), int.from_bytes(signature[32:], "big"))
try:
key.verify(der, f"{parts[0]}.{parts[1]}".encode(), ec.ECDSA(hashes.SHA256()))
except InvalidSignature:
return {"ok": False, "reason": "signature"}
if claims.get("iss") != ISSUER:
return {"ok": False, "reason": "iss"}
allowed = [audience] if isinstance(audience, str) else list(audience)
if claims.get("aud") not in allowed:
return {"ok": False, "reason": "aud"}
if not nonce or claims.get("nonce") != nonce:
return {"ok": False, "reason": "nonce"}
if not isinstance(claims.get("exp"), int) or claims["exp"] < now:
return {"ok": False, "reason": "exp"}
if not isinstance(claims.get("jti"), str) or not use_jti(claims["jti"], claims["exp"]):
return {"ok": False, "reason": "replay"}
return {"ok": True, "application": claims.get("application"), "claims": claims}
Call it as verify_application_token(token, load_jwks, audience, state).
PHP
PHP 8.0 or later with the openssl extension:
<?php
// Verify an Apply with certo token on your server. PHP 8.0 or later with the openssl extension.
const CERTO_ISSUER = 'https://certo.bio';
const CERTO_JWKS_URL = 'https://certo.bio/.well-known/certo-apply-jwks.json';
function certo_b64(string $part): string
{
$raw = base64_decode(strtr($part, '-_', '+/') . str_repeat('=', (4 - strlen($part) % 4) % 4), true);
if ($raw === false) {
throw new InvalidArgumentException('not base64url');
}
return $raw;
}
// The public keys, fetched again after five minutes or when a token names a key not seen yet.
// The cache lives for one request here; keep it in APCu or your cache to share it.
function certo_load_jwks(?string $kid = null): array
{
static $cache = ['at' => 0, 'jwks' => ['keys' => []]];
$known = in_array($kid, array_column($cache['jwks']['keys'], 'kid'), true);
if (!$known || time() - $cache['at'] > 300) {
$cache = ['at' => time(), 'jwks' => json_decode(file_get_contents(CERTO_JWKS_URL), true, 512, JSON_THROW_ON_ERROR)];
}
return $cache['jwks'];
}
// A P-256 public key from its JWK, as PEM.
function certo_pem(array $jwk): string
{
$der = hex2bin('3059301306072a8648ce3d020106082a8648ce3d030107034200') . "\x04" . certo_b64($jwk['x']) . certo_b64($jwk['y']);
return "-----BEGIN PUBLIC KEY-----\n" . chunk_split(base64_encode($der), 64, "\n") . "-----END PUBLIC KEY-----\n";
}
// A JWS signature (r and s, 32 bytes each) as the DER openssl_verify reads.
function certo_der(string $signature): string
{
$int = function (string $n): string {
$n = ltrim($n, "\x00");
if ($n === '' || ord($n[0]) > 0x7f) {
$n = "\x00" . $n;
}
return "\x02" . chr(strlen($n)) . $n;
};
$seq = $int(substr($signature, 0, 32)) . $int(substr($signature, 32));
return "\x30" . chr(strlen($seq)) . $seq;
}
/**
* $jwks the key set, or Closure::fromCallable('certo_load_jwks') (called with the token's kid)
* $audience the button's id (ao_..., ap_... or as_...), or an array of your ids
* $nonce the state you put on the button or in the apply session, kept on your server
* $useJti fn(string $jti, int $exp): bool, true the first time only. Keep the ids where
* every server of yours sees them (a database table or Redis, until exp).
* Answers ['ok' => true, 'application' => ..., 'claims' => ...] or ['ok' => false, 'reason' => ...].
*/
function certo_verify_application_token(string $token, array|Closure $jwks, string|array $audience, ?string $nonce, callable $useJti, ?int $now = null): array
{
$now ??= time();
$parts = explode('.', $token);
if (count($parts) !== 3) {
return ['ok' => false, 'reason' => 'malformed'];
}
try {
$header = json_decode(certo_b64($parts[0]), true, 512, JSON_THROW_ON_ERROR);
$claims = json_decode(certo_b64($parts[1]), true, 512, JSON_THROW_ON_ERROR);
$signature = certo_b64($parts[2]);
} catch (Throwable $e) {
return ['ok' => false, 'reason' => 'malformed'];
}
if (!is_array($header) || !is_array($claims)) {
return ['ok' => false, 'reason' => 'malformed'];
}
if (($header['alg'] ?? null) !== 'ES256') {
return ['ok' => false, 'reason' => 'alg'];
}
$set = is_array($jwks) ? $jwks : $jwks($header['kid'] ?? null);
$jwk = null;
foreach ($set['keys'] ?? [] as $k) {
if (($k['kid'] ?? null) === ($header['kid'] ?? null)) {
$jwk = $k;
}
}
if ($jwk === null) {
return ['ok' => false, 'reason' => 'kid'];
}
if (strlen($signature) !== 64 || openssl_verify($parts[0] . '.' . $parts[1], certo_der($signature), certo_pem($jwk), OPENSSL_ALGO_SHA256) !== 1) {
return ['ok' => false, 'reason' => 'signature'];
}
if (($claims['iss'] ?? null) !== CERTO_ISSUER) {
return ['ok' => false, 'reason' => 'iss'];
}
if (!in_array($claims['aud'] ?? null, (array) $audience, true)) {
return ['ok' => false, 'reason' => 'aud'];
}
if (!$nonce || ($claims['nonce'] ?? null) !== $nonce) {
return ['ok' => false, 'reason' => 'nonce'];
}
if (!is_int($claims['exp'] ?? null) || $claims['exp'] < $now) {
return ['ok' => false, 'reason' => 'exp'];
}
if (!is_string($claims['jti'] ?? null) || !$useJti($claims['jti'], $claims['exp'])) {
return ['ok' => false, 'reason' => 'replay'];
}
return ['ok' => true, 'application' => $claims['application'] ?? null, 'claims' => $claims];
}
Call it as certo_verify_application_token($token, Closure::fromCallable('certo_load_jwks'), $audience, $state, $useJti), with $useJti backed by your database or cache.
These samples are run against tokens certo's own signing code makes, every time certo's code changes.
The application
The same object on the token, in the message and from GET /v1/applications/{id}:
{
"type": "certo.application",
"id": "3f6b1a52-8c4d-4e9f-a1b2-c3d4e5f60718",
"organisation_id": "01a17b20-5d3c-4e8f-9a1b-2c3d4e5f6a7b",
"position_id": null,
"job": { "ref": "JOB-42", "title": "Backend engineer", "hiring_company": "Acme Robotics", "url": "https://jobs.hireline.example/job-42" },
"state": "st-9d1e5c7a2b",
"submitted_at": "2026-11-20T09:59:58Z",
"withdrawn_at": null,
"terms": { "scope_types": ["education", "employment"], "include_contact": true, "include_birth_date": false, "birth_date_reason": null, "requirements": null, "source": "general" },
"session_id": null,
"candidate": {
"id": "7a1e2c3d-4b5f-4a6e-8d9c-0b1a2c3d4e5f",
"name": "Mara Lindqvist",
"passport_url": "https://certo.bio/mara-lindqvist",
"identity": { "verified": true, "verified_at": "2026-11-02T09:00:00Z" },
"contact": [{ "kind": "email", "label": "Personal", "value": "mara@example.org", "verified_at": "2026-11-02T09:05:00Z" }]
},
"records": [{
"id": "b2c3d4e5-0000-4000-8000-000000000001",
"type": "employment",
"title": "Software engineer",
"organisation": "Northwind Logistics",
"period": { "from": "2021-03", "to": "2025-08" },
"assurance": "verified",
"request_outcome": null,
"confirmed_by": "Northwind Logistics HR",
"confirmed_fields": ["employer", "period"],
"claimed_fields": ["position"],
"withheld": [],
"certificate_url": "https://certo.bio/v/c0ffee00-0000-4000-8000-000000000002",
"source": "organisation",
"stated": { "position": "Software engineer", "employer": { "legal_name": "Northwind Logistics" }, "period": { "start": "2021-03", "end": "2025-08" } },
"removed": false
}],
"requirements": [
{ "key": "identity", "state": "ready", "counts": {}, "detail": null },
{ "key": "work_history", "state": "waiting", "counts": { "ready": 1, "total": 2 }, "detail": null }
],
"custom_data": { "board_job_id": 9912 }
}
candidate.idis the candidate's id in the API:GET /v1/candidates/{id}reads the passport again later, on the same access.recordsare in the shapeGET /v1/candidates/{id}answers: each record's outcome, who confirmed it and exactly which fields, what stays Claimed (claimed_fields), and silence asrequest_outcome: "no_response". Only the kinds the terms open.candidate.contactis there only where the terms include contact; otherwise it is null.requirementsis the checklist when the candidate applied: each itemready,waitingormissing.state,session_idandcustom_dataare yours, as you sent them.
Answer fast, keep it once
The token lives ten minutes, so verify it as it arrives. Store the application by its id: a candidate who applies again for the same job sends the same id with the terms of now.