Verify field tokens in your backend
A field worker signs in to the platform, not to your application. The device then calls your API with two headers, and your backend verifies them on every request. It never sees a PIN and hosts no login page.
POST /api/gates/open HTTP/1.1Authorization: DPoP eyJhbGciOiJSUzI1NiIs... # the field access token (RS256)DPoP: eyJhbGciOiJFUzI1NiIs... # a proof, signed by the device key (ES256)Background: Field-worker identity. The device side of the same exchange is in Enrol a device and sign in.
What verification checks
Section titled “What verification checks”Both checks must pass. The SDK verifiers do all of them, in this order.
The access token
| Check | Rule |
|---|---|
| Algorithm | RS256 only. Anything else, including none and ES256, is refused. |
| Signature | Against the platform’s published keys (OIDC discovery and JWKS, cached and refetched when a kid is unknown). |
typ (JOSE header) |
fc-field+jwt. |
token_use |
field. A platform API token is refused here, and a field token is refused as an API credential. |
iss, exp, nbf |
The platform’s base URL; time checks with a small skew (60 s). |
aud |
Your application code. A token issued for another application is refused. |
pcr |
A token that may only change the PIN is refused (403 PIN_CHANGE_REQUIRED in the frameworks). |
The proof
| Check | Rule |
|---|---|
| Algorithm and key | ES256; the header carries the device’s public P-256 key (a private member is refused). |
| Binding | The key’s RFC 7638 thumbprint equals the token’s cnf.jkt. A stolen token without the device key is useless. |
htm |
The request method. |
htu |
Your public base URL plus the request path, no query. Never X-Forwarded-*, which a client can set, and never the Host header, except in the Laravel SDK’s multi-origin mode (see Pitfalls). |
ath |
The SHA-256 hash of the access token. |
iat |
Within a window of now. The SDK default is 5 minutes; the frameworks accept 24 hours because field devices keep bad time, and use a nonce for freshness. |
The refusal reasons are the same strings in every SDK (they are also what the shared fixtures expect):
malformed, wrong_typ, wrong_token_use, wrong_aud, expired, invalid_token, pcr,
missing_proof, invalid_proof, jkt_mismatch, htm_mismatch, htu_mismatch, ath_mismatch,
stale_proof. Answer any of them with 401 and WWW-Authenticate: DPoP error="invalid_token"; do not
tell the caller the reason, log it. A failure to fetch the platform’s keys is not a verdict: answer
503 so the device retries.
Verify with an SDK
Section titled “Verify with an SDK”Go, TypeScript, PHP and Java have a field verifier. The Rust SDK does not yet.
import "github.com/flowcatalyst/go-sdk/auth" // module github.com/flowcatalyst/go-sdk, package auth
v := auth.NewFieldTokenVerifier(auth.FieldTokenVerifierConfig{ Issuer: "https://platform.example.com", // the platform base URL and the tokens' iss AppCode: "yard-gate", // tokens must be addressed to this BaseURL: "https://api.example.com", // this service's public URL, for the proof's htu})
mux.Handle("POST /api/gates/open", auth.FieldMiddleware(v)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { p, _ := auth.FieldPrincipalFrom(r.Context()) // p.WorkerID, p.WorkerCode, p.ClientIdentifier, p.DeviceID, p.DeviceMode, p.Actor, p.Test ...})))FieldMiddleware panics at construction without BaseURL: a wiring error is caught at start-up
rather than as 401s at runtime. To verify by hand, call
v.Verify(ctx, authorizationHeader, dpopHeader, method, fullURL); it returns a *FieldPrincipal or
a *FieldError whose Reason is one of the auth.FieldReason* constants.
import Fastify from "fastify";import { fieldAuth } from "@flowcatalyst/sdk/fastify";
const app = Fastify();await app.register(fieldAuth, { issuer: "https://platform.example.com", appCode: "yard-gate", publicBaseUrl: "https://api.example.com", // htu = this + the request path});
app.post("/api/gates/open", { preHandler: app.fcField.require() }, async (req) => { const p = req.fieldPrincipal!; // workerId, workerCode, deviceId, clientId, appCode ...});fieldAuth adds no global hook; it runs only on routes that use app.fcField.require() and never
touches request.principal, so it sits beside the bearer plugin. Without Fastify:
import { FieldTokenVerifier, FieldError } from "@flowcatalyst/sdk";
const verifier = new FieldTokenVerifier({ issuer, appCode: "yard-gate" });try { const p = await verifier.verify(authHeader, dpopHeader, "POST", "https://api.example.com/api/gates/open");} catch (e) { if (e instanceof FieldError) console.log(e.reason); // "expired", "htu_mismatch", ...}A key-fetch failure rejects with FieldVerifierUnavailableError: answer 503.
FLOWCATALYST_FIELD_APP_CODE=yard-gateFLOWCATALYST_FIELD_APP_BASE_URL=https://api.example.com # defaults to APP_URL; htu = this + pathRoute::post('/api/gates/open', function (Request $request) { /** @var \FlowCatalyst\Auth\Field\FieldPrincipal $worker */ $worker = $request->user(); // or Auth::guard('field')->user() $worker->workerId; $worker->workerCode; $worker->clientIdentifier; $worker->deviceId;})->middleware('fc.field');The issuer and keys come from FLOWCATALYST_BASE_URL. A pcr token answers
403 {"error":"PIN_CHANGE_REQUIRED"}, any other refusal 401 {"error": <reason>}, and a key-fetch
failure 503. To verify directly:
app(\FlowCatalyst\Auth\Field\FieldTokenVerifier::class)->verify($authorization, $dpop, $method, $fullUrl)
returns a FieldPrincipal or throws FieldTokenException (->reason). Optional settings:
FLOWCATALYST_FIELD_PROOF_MAX_AGE (seconds, default 300) and FLOWCATALYST_FIELD_CLOCK_SKEW
(default 60).
var verifier = FieldTokenVerifier.builder() .issuer("https://platform.example.com") .appCode("yard-gate") .build();
switch (verifier.verify(authorization, dpop, "POST", "https://api.example.com/api/gates/open")) { case FieldVerification.Valid v -> handle(v.principal()); case FieldVerification.Invalid i -> respond(401, i.reason()); case FieldVerification.Unavailable u -> respond(503, "unavailable");}You pass the full public URL yourself (scheme, host and path; the query is ignored). The verifier
is thread-safe and caches the platform’s keys. Other builder options: jwksUrl, httpClient,
jwksRefreshInterval, clockSkew, proofMaxAge, clock.
The principal fields are the same across SDKs: worker id and code, name, client id and identifier,
application code, device id (empty on an unenrolled device) and mode (PERSONAL, SHARED or
UNENROLLED), the session (login family) id, amr (how the worker authenticated), the token’s
expiry, the key thumbprint, and three optional extras:
actor: set when someone else is signed in as the worker (a supervisor, or an administrator through a console sign-in code). The other fields still describe the worker. Record both when you audit.test: true for a test identity.linkedPrincipalId: the platform user an administrator linked to the worker. For audit correlation only. It grants nothing, and no permission, role or tier comes from it.
Replay protection and nonces
Section titled “Replay protection and nonces”The SDK verifiers check the proof’s iat window and nothing more. They do not check a nonce or
remember proof ids. For most read-only APIs that is acceptable. If a replayed proof matters (opening a
gate, releasing a load), either use a framework (below), which adds both, or add your own: a proof is
bound to one method and one URL and to the access token, so replay is limited to that same request
within the window.
Use a framework
Section titled “Use a framework”The Go and Java application frameworks provide the verifier as an opt-in module, with application nonces and a replay cache built in, and map the worker into the request context. They are off by default.
m, err := d.Build(ctx, b, auth.SessionStore(authredis.Factory(clients)), auth.Application(fw.MustApplicationCode("orders")), auth.FieldWorkers( auth.MapFieldPermissions(auth.FieldPermissionsByDeviceMode( []string{"orders:thing:create", "orders:thing:view"}, // PERSONAL device []string{"orders:thing:view"}, // SHARED kiosk )), auth.FieldReplay(replay), // a shared cache when there is more than one replica ),)Also pass auth.DeclareFieldWorkers() to auth.Declare so the OpenAPI document lists the dpop
scheme; Build fails when only one of the two is given.
AuthModule.builder() .application(new ApplicationCode("orders")) // a token's audience must equal this .fieldWorkers(FieldOptions.builder() .permissions(FieldPermissions.byDeviceMode( Set.of("orders:gate:open", "orders:gate:view"), Set.of("orders:gate:view"))) .replayCache(lookup -> RedisFieldReplayCache.create(lookup.get(RedisConnections.class).defaultInstance())) .build()) .build()What the framework adds:
- Application nonces. The platform’s own nonces are single-use and stored there, so your
application issues its own, statelessly: a MAC of the current five-minute bucket under a key derived
(HKDF-SHA256) from your cookie key, valid in the current and the previous bucket under any configured
cookie key. Every answer to a
DPoPrequest carries a freshDPoP-Nonce; a missing or bad nonce is401 USE_DPOP_NONCEand the device library retries once. Rotatingauth.cookie-keysdoes not break devices. - A replay cache. Each proof’s
jtiis remembered per device key for 11 minutes. The default is in memory and logs one warning: with several replicas a captured proof can be replayed against another replica inside the window, so pass the Redis cache (keyfw:dpop:{jkt}:{jti}). A cache that cannot be reached answers503; a proof is never accepted unchecked. - Required settings. The application code and
auth.cookie-keys; without them start-up fails with a message that says which. The public base URL (auth.public-base-url) is thehtubase. - The right client. A field worker belongs to exactly one client. If your client selector names a
different client from the token’s (a route like
/api/clients/globex/...for a worker ofacme) the request is403 CLIENT_NOT_PERMITTEDbefore your permission mapping runs, so a handler need not compare them.
Permissions are yours to grant
Section titled “Permissions are yours to grant”A field token carries no platform roles and no permissions. The platform stores only “this worker may sign in to that application”. What the worker may do inside it comes from your own data:
- A fixed set for every worker, or one set per device mode (
byDeviceMode) so a shared kiosk gets less than a personal phone. The default grants none, so a route that requires a permission refuses field workers until you map them. - A resolver when you keep roles in your own database:
auth.FieldPermissionsFrom(func(ctx, p auth.FieldPrincipal) ([]string, error))in Go, orpermissionResolver((request, worker) -> ...)in Java. It runs on every authenticated field request after the proof is verified. An error answers503 UNAVAILABLE, never “no permissions”, so a store outage makes the device retry instead of being locked out.
Routes can be made field-only or never-field with auth.RequireSource(auth.SourceField) (Go) and
Auth.requireSource(Authenticated.Source.FIELD) (Java).
Before a high-value action: ask the platform
Section titled “Before a high-value action: ask the platform”An access token lives ten minutes. If an administrator suspends a worker or revokes a device, the refresh stops at once, but a token already issued stays valid at your backend until it expires. Normally that is fine. For an action that cannot wait (open a gate, release a load), ask the platform:
POST /api/field-tokens/introspectAuthorization: Bearer <service account token>Content-Type: application/json
{ "token": "<the field access token>" }The answer is {"active": true, "sub": "fwu_...", "workerCode": "W001", ...} or {"active": false}.
It is active only while the token is unexpired, its login family has a live session, the worker is
active and, when the token names a device, the device is active. A token that fails any check, or
belongs to a client or application the caller cannot reach, is simply inactive, never an error. The
caller needs the permission platform:iam:field-token:introspect (the Laravel SDK has
FlowCatalyst::introspectFieldToken($token), the TypeScript SDK client.introspectFieldToken(token)).
The frameworks wrap this as RequireLiveField (Java, framework-flowcatalyst) and
fc.RequireLiveField(30*time.Second) (Go). It remembers an active answer per login family for the time
you give (zero means always ask) and never past the token’s expiry, never remembers an inactive answer,
and fails closed: if the platform cannot be asked the request is 503.
Revocation events
Section titled “Revocation events”The platform emits platform:iam:field-worker:suspended, platform:iam:field-device:revoked and
platform:iam:field-session:revoked (and others for creation, PIN resets, badges and so on). Subscribe to
them to clean up application state, such as cached work assignments or open gate sessions. They are
not how token validity is decided: tokens expire on their own within ten minutes.
err := flowcatalyst.OnFieldRevocation(fc.Receivers(), func(ctx context.Context, cx fw.Context, e flowcatalyst.FieldRevocation) error { switch e := e.(type) { case flowcatalyst.WorkerSuspended: // e.WorkerID, e.ClientID case flowcatalyst.DeviceRevoked: // e.DeviceID, e.ClientID case flowcatalyst.SessionRevoked: // e.SessionID, e.WorkerID, e.DeviceID, e.ClientID, e.Reason } return nil // an error is a transient failure: the platform delivers again})Declare the subscription so the definition sync registers it. The handler may run more than once for
one event, so make it idempotent. An application that serves push streams ends a
revoked worker’s streams from the same handler (EndStreams in Go, endStreams in Java).
Test with the shared fixtures
Section titled “Test with the shared fixtures”The platform publishes vectors that every verifier must agree with:
api/field-fixtures/cases.json and jwks.json in the platform repository. Each case is a token, a
proof, a method, a URL and a time, with the expected result: valid or the refusal reason. There are
23 cases, among them a valid unenrolled device, a supervisor and an administrator acting as the
worker, a test identity, a linked worker and a worker signed in with an unlock key (amr
["hwk","uv"]), and the refusals: wrong typ, wrong token_use, wrong
audience, expired, missing exp, a pcr token, a missing proof, a proof from another device, a
wrong method, URL or ath, a stale proof, an API token presented as a field token, a non-RS256
token and a tampered signature. Configure your verifier with the fixture issuer, application code and
JWKS, run each case at its own now, and compare.
The frameworks also ship test helpers that mint a field token and a valid or deliberately broken
proof: authtest.NewFieldDevice() and Testing.FieldRequest (Go), TestFieldDevice and
AuthTesting.fieldRequest (Java). They work only with APP_ENV=test.
Pitfalls
Section titled “Pitfalls”- Signing the wrong URL. The
htucheck uses your configured public base URL, so behind a proxy or a path prefix the base URL must include everything the device calls, not what your process sees. - Using the Host header. Do not build the proof’s URL from it, and do not use
X-Forwarded-*. The SDKs never do, with one deliberate exception: the Laravel SDK, whenapp_base_urllists several origins or a wildcard for an application with a host per client, reads the request’s host only to choose among the origins you listed (a host matching none is refused ashtu_mismatch). That needs wildcards over zones you wholly control, trusted proxies configured, and aFieldClientCheckbound. See the Laravel SDK. - Treating the token as a user session. There is no cookie and no CSRF for field requests.
- Looking for roles in the token. There are none. Map permissions from your own store.
- Several replicas, in-memory replay cache. Use Redis, or accept the window.