Enrol a device and sign in
This guide takes a device from nothing to a signed-in field worker making requests to your backend. It assumes you have picked a library (Choosing a field library) and that an administrator has created the worker, set a PIN and granted the application (Manage workers, devices, badges and impersonation). The model behind it is in Field-worker identity; the wire detail is in the field protocol reference.
Set up the session object
Section titled “Set up the session object”Everything goes through one object: FieldAuth in field-js, FieldClient in field-react-native,
FieldSession in field-android.
import { FieldAuth, FieldAuthError, defaultProviders } from "@flowcatalyst/field-js";
const { keys, store } = defaultProviders(); // bridge providers inside a RN WebView, else WebCrypto + IndexedDB
const auth = new FieldAuth({ platformUrl: "https://platform.example.com", // optional until enrolment: a QR payload carries it appCode: "yard-gate", // the application the worker signs in to clientIdentifier: "acme", // needed for worker-code sign-in on an unenrolled device keys, store,});
await auth.restore(); // loads a stored device record and session, if anyIn a React Native app with native screens use FieldClient from
@flowcatalyst/field-react-native instead (see the Kotlin and React Native examples below).
val session = FieldSession.get(applicationContext, FieldConfig( platformUrl = "https://platform.example.com", appCode = "yard-gate", clientIdentifier = "acme", requireUnlock = UnlockPolicy(afterColdStart = true, afterBackground = 5.minutes),))session.restore() // optional: waits for the stored session to loadFieldSession.get is the process-wide owner. Call it from anywhere with the same config; a
different config throws. Do not run a service that uses it in a separate process.
import { FieldClient } from "@flowcatalyst/field-react-native";
const field = new FieldClient({ platformUrl: "https://platform.example.com", appCode: "yard-gate", clientIdentifier: "acme", requireUnlock: { afterColdStart: true, afterBackgroundMs: 5 * 60_000 },});const { state, session } = await field.restore(); // SignedOut | SignedIn | LockedclientIdentifier is the client’s identifier (the same value the tokens carry as
client_identifier). It is needed when a worker types a worker code on a device that is not
enrolled, because a worker code is only unique within a client. An enrolled device already knows its
client, and a badge carries its own.
Enrol a device (optional)
Section titled “Enrol a device (optional)”Enrolment is optional. A worker code and PIN work from any device: the library makes its key without telling the platform first, and the tokens are still bound to it. Enrol when you want what only a known device can give:
- remote suspend and revoke, and a failure budget of its own;
- a restriction to certain applications, or assignment to one worker;
- badge-only sign-in, biometric unlock and unlock keys (personal devices only);
- a client that requires enrolment (
requireEnrolledDevicein the field policy), where an unknown key is refused asUNKNOWN_DEVICE.
An administrator opens Field Devices in the console, chooses the client and presses Enrol
Device. The dialog asks for the mode (PERSONAL for one worker’s own device, SHARED for a pool
device used by many in turn), the applications the device may run, an optional assigned worker
(personal devices only) and an optional label. The result is an enrolment code with a QR code,
valid for 10 minutes and single use. It is shown once.
The QR payload is fcfield:1:<platform base URL>:<code>; the code is the last segment. Scan it in
your app and hand the text to the library.
const { platformUrl, code } = auth.parseEnrolmentQr(scannedText); // not needed: enrol() accepts the whole QR text tooconst device = await auth.enrol(scannedText, { label: "Depot 3 scanner" });// device = { deviceId, mode, clientId, appCodes, platformUrl }, stored under "fc.field.device"session.enrol("fcfield:1:https://platform.example.com:ABCDE12345", DeviceInfo(model = Build.MODEL))await field.enrol(qrPayloadOrCode, { label: "Truck 7" });Enrolment registers the device’s public key. The proof you send with it must be signed by that same
key. If the code is unknown, used or expired the call fails with INVALID_ENROLMENT_CODE; a key that
is already enrolled gets 409 DEVICE_KEY_EXISTS. If the client’s policy requires attestation the
platform currently cannot verify one, so enrolment answers 422 ATTESTATION_REQUIRED: leave
requireAttestation off for now.
Sign in with a worker code and PIN
Section titled “Sign in with a worker code and PIN”import { FieldAuthError, definePinPad } from "@flowcatalyst/field-js";
definePinPad(); // registers <fc-pin-pad>// <fc-pin-pad length="6" scrambled label="Enter your PIN"></fc-pin-pad>
pad.addEventListener("pin", async (e) => { try { const session = await auth.login({ workerCode: "W001", pin: (e as CustomEvent).detail.pin }); showHome(session.worker.name); } catch (err) { if (err instanceof FieldAuthError) showError(err); }});session.login(LoginCredentials(workerCode = "W001", pin = "483920"))await field.login({ workerCode: "W001", pin: "483920" });<fc-pin-pad> (field-js) is a framework-free keypad built for gloves: a 3 by 4 grid with targets of
at least 64 px, dots instead of digits, length (default 6), scrambled (shuffle the digits each
time it is shown, so a watcher cannot read finger positions), disabled and label. It emits a
pin event with detail.pin when the last digit is in and then clears itself. It never writes the PIN
to an attribute, the DOM, storage or the console. Use it, or your own pad, but pass the PIN straight
to login.
The result is a Session: the worker (id, workerCode, name), the application, and the three
deadlines expiresAt (the access token), idleExpiresAt and refreshExpiresAt (the absolute end of
this login). pinChangeRequired is true when the worker has a temporary PIN.
Sign in with a badge
Section titled “Sign in with a badge”A printed badge is a QR code holding a token that starts FWB1. A camera scan or a scanner’s
keyboard wedge gives the same text; normaliseBadgeToken strips the whitespace and control
characters a wedge adds (it ends the string with Enter) and upper-cases it.
import { normaliseBadgeToken } from "@flowcatalyst/field-js";
await auth.login({ badgeToken: normaliseBadgeToken(scanned), pin });By default a badge identifies the worker and the PIN is still required (amr is ["badge","pin"]).
If the client’s policy allows badge-only sign-in, call login({ badgeToken }) without a PIN, but
only on an enrolled device: on a device that is not enrolled the PIN is always required, so a
photocopied badge does not work from an arbitrary phone. A missing PIN where one is needed is
PIN_REQUIRED.
Temporary PINs and changing the PIN
Section titled “Temporary PINs and changing the PIN”An administrator’s reset gives a temporary PIN and sets pinChangeRequired. The session you get
back is limited: it works only for changing the PIN. The library raises a pinChangeRequired event
(field-js, field-react-native PinChangeRequired), and your app shows a change screen:
auth.addEventListener("pinChangeRequired", () => showChangePin());await auth.changePin({ currentPin, newPin }); // then refreshes into a full sessionThe platform rejects weak PINs with PIN_POLICY and a violations list: too short, all one digit,
a straight run (123456, 654321), a common PIN, or the worker’s own code. The minimum length is
the client’s policy (six by default, four to twelve allowed).
Failures
Section titled “Failures”All libraries report platform failures as an error with a code (FieldAuthError in field-js and
field-react-native, FieldAuthException in field-android). The ones to handle on a sign-in screen:
| Code | Meaning | What to do |
|---|---|---|
INVALID_CREDENTIALS |
Wrong PIN, unknown worker, unknown or revoked badge. Deliberately not more specific. | Ask again. |
WORKER_LOCKED_TEMPORARILY |
Soft lock after repeated failures (five by default, 15 minutes). retryAfter says when. |
Show the wait. |
WORKER_LOCKED |
Hard lock (ten failures by default). | A supervisor or administrator must unlock the worker. |
PIN_RESET_REQUIRED |
403. The worker’s PIN was set under an app key the platform no longer has, so it cannot be checked. It is not a wrong PIN: it is not counted as a failure and there is no lockout. The same answer comes from act-as (the supervisor’s own PIN) and from changing a PIN. | Show “Ask your supervisor to reset your PIN”. Test for it with isPinResetRequired (field-js and field-react-native) or FieldAuthException.isPinResetRequired (field-android). A supervisor resets the PIN. |
TOO_MANY_ATTEMPTS |
The device’s, address’s or client’s hourly failure budget is spent. retryAfter. |
Wait. |
NO_APP_ACCESS |
The PIN was right but the worker has no grant for this application, the application or client is inactive, or the device is not enrolled for it. The reason is only in the console’s sign-in history. | Ask an administrator. |
UNKNOWN_DEVICE |
The client requires enrolled devices and this key is not enrolled. | Enrol. |
DEVICE_SUSPENDED, DEVICE_REVOKED |
An administrator disabled the device. | Contact the administrator. |
CLIENT_MISMATCH |
The clientIdentifier names a different client from the enrolled device’s. |
Fix the config. |
PIN_REQUIRED |
Badge sign-in needs the PIN here. | Ask for it. |
NETWORK |
The platform was not reached. | Retry. |
Throttling and lock checks run before the PIN check and grant checks, so none of these answers lets someone learn whether a worker exists or which applications they use.
Keep the session, and know when it ends
Section titled “Keep the session, and know when it ends”The library refreshes the access token (ten minutes) before it expires and rotates the refresh token on every refresh. Concurrent callers share one refresh request. Idle and absolute limits depend on the device:
| Device | Idle limit | Absolute limit |
|---|---|---|
Enrolled PERSONAL |
2 hours | the shift cap, 14 hours by default |
Enrolled SHARED |
15 minutes | 12 hours |
| Not enrolled | 15 minutes | 12 hours |
The limits come from the client’s field policy. Listen for the end of the session and send the worker back to the sign-in screen:
auth.addEventListener("sessionEnded", (e) => goToSignIn((e as CustomEvent).detail.reason));auth.addEventListener("locked", () => showWorkerLocked());session.addListener { event -> when (event) { is FieldEvent.SessionEnded -> goToSignIn(event.reason) is FieldEvent.ExpiryWarning -> askForNewSignInAtNextStop(event.remaining) else -> {} }}const off = field.on("SessionEnded", ({ reason }) => navigateToSignIn(reason));A session ends for any of: logout, INVALID_GRANT (the refresh token was spent, revoked or reused;
suspending a worker causes this at the next refresh), SESSION_EXPIRED (idle or absolute limit),
DEVICE_REVOKED, DEVICE_SUSPENDED, UNKNOWN_DEVICE, NO_APP_ACCESS, or an invalid_token that
survives a refresh. Presenting a spent refresh token from any other key is treated as theft and
revokes the whole login family. A refresh retried within 60 seconds of its rotation with the same key
is accepted as a lost-response retry.
Long shifts: keepAlive
Section titled “Long shifts: keepAlive”A worker who is busy but not touching the screen (a driver on a trip) would hit the idle limit.
Turn on keepAlive only while the work is genuinely active. It is a feature of the native libraries (field-android and field-react-native), not of field-js. The native owner then refreshes before
the idle deadline for as long as it is on; it ends with the session. It uses a coroutine, not an
Android alarm, so the foreground service has to keep the process alive.
session.keepAlive(true) // trip startedsession.keepAlive(false) // trip endedThe native libraries also raise an ExpiryWarning 30 and 10 minutes before the absolute limit (configurable),
so the app can ask for a fresh sign-in at a stop rather than mid-delivery.
Biometric unlock
Section titled “Biometric unlock”A biometric on its own never says who someone is. The app unlock below only unlocks a session a PIN
already started, on an enrolled PERSONAL device, and never for an impersonated session. To sign a
worker in again with a biometric after a session has ended, use an unlock key,
which the platform verifies.
- field-js: pass
biometricUnlock: truetoFieldAuth. The refresh token is then stored behind the biometric (through the native bridge store) andauth.unlock()reads it and refreshes. If the phone’s biometrics changed (KEY_INVALIDATED, raised asBIOMETRIC_INVALIDATED), the stored token is cleared and you ask for the PIN. - field-android and field-react-native: the refresh token is stored without a prompt so
background refresh works. The biometric gates the screens: with
UnlockPolicythe state becomesLockedafter a cold start or time in the background, and the UI callsunlock(activity, "Unlock")(Kotlin) orfield.unlock("Unlock")(React Native).Lockednever blocks signed requests orkeepAlive.
Unlock keys: sign in with a fingerprint or face
Section titled “Unlock keys: sign in with a fingerprint or face”An unlock key lets a worker whose session has ended (the shift limit, the idle limit, a sign-out) sign
in again on their own phone without the PIN. The phone holds a hardware key that signs only after a
strong biometric match; the platform holds its public half, verifies a signature over a fresh
challenge, and issues a new session with amr ["hwk","uv"]. The PIN is never stored. The idea and
the rules are in Field-worker identity.
What has to be true for the library to offer it:
- The client’s field policy has Unlock keys on (or the application’s override does). It is off by default.
- The device is enrolled and
PERSONAL, the session is the worker’s own (not a supervisor’s act-as or a sign-in code), and it began with the PIN on this device within the last 10 minutes. The platform says so in every sign-in and refresh answer (Session.unlockKeys), and the library computesunlockKeyAvailability()from that with no network request. - Android 11 (API 30) or later, a phone with secure hardware, and a strong biometric enrolled. field-android 0.6.0 or later; field-react-native on Android needs field-android 0.6.0 or later too (its default version is the one it was built against).
- field-js does not support unlock keys. In a browser or a WebView page,
unlockKeyAvailability()is always"UNSUPPORTED",unlockKey()isnull,enableUnlockKey()andloginWithUnlockKey()reject withUNLOCK_KEYS_UNSUPPORTED, anddisableUnlockKey()does nothing. Offer it from the native side of a React Native app.
The method names differ a little by platform; the flow is the same: check availability after the
PIN sign-in, ask the worker, enableUnlockKey; on the sign-in screen, if unlockKey() names a worker,
loginWithUnlockKey; any failure means “show the PIN pad”.
// right after a PIN sign-in, while the register window is openif (session.unlockKeyAvailability() == UnlockKeyAvailability.AVAILABLE && workerSaysYes()) { session.enableUnlockKey(activity, UnlockKeyPrompt(title = "Use your fingerprint to sign in", cancel = "Not now"))}// on the sign-in screentry { session.loginWithUnlockKey(activity, UnlockKeyPrompt(title = "Sign in", cancel = "Use PIN"))} catch (e: FieldAuthException) { showPinPad(reason = e.code)}session.disableUnlockKey() // switch it off on this phone; works signed outif try await field.unlockKeyAvailability() == .available /* and the worker said yes */ { _ = try await field.enableUnlockKey(prompt: UnlockKeyPrompt(title: "Use Face ID to sign in next time", cancel: "Not now"))}if let key = try await field.unlockKey() { // key.workerCode, key.workerName _ = try await field.loginWithUnlockKey(prompt: UnlockKeyPrompt(title: "Sign in as \(key.workerName)", cancel: "Use PIN"))}try await field.disableUnlockKey()if ((await field.unlockKeyAvailability()) === "AVAILABLE" && (await askWorker())) { await field.enableUnlockKey({ title: "Use your fingerprint to sign in", cancel: "Not now" });}if (await field.unlockKey()) { try { await field.loginWithUnlockKey({ title: "Sign in", cancel: "Use PIN" }); } catch (e) { showPinPad((e as FieldAuthError).code); }}await field.disableUnlockKey();Things to handle:
unlockKeyAvailability()answersAVAILABLE,ENABLED(this worker already holds a key), or the reason it is not:POLICY_OFF,NOT_ENROLLED,SHARED_DEVICE,NOT_SIGNED_IN,IMPERSONATING,PIN_SIGN_IN_REQUIRED(the register window has closed, or the app restarted since the answer; the next refresh brings it back),OTHER_WORKER(one key per phone),OS_TOO_OLD,NO_SECURE_HARDWARE,BIOMETRIC_NOT_ENROLLED,BIOMETRIC_UNAVAILABLE,ATTESTATION_REQUIREDandUNSUPPORTED.- Failures keep or drop the key.
UNLOCK_KEY_INVALID,UNLOCK_KEY_INVALIDATED(the phone’s biometrics changed),UNLOCK_KEYS_DISABLEDand a revoked device delete the local key;PIN_REAUTH_REQUIRED, a lock,NETWORKand a cancelled prompt keep it. The full table is in the field-android README. - The prompt text is yours. The library has none: pass
title,canceland an optionalsubtitle. Face ID needsNSFaceIDUsageDescription. - iOS cannot attest a key. A client whose policy sets unlock key attestation to
REQUIREDcannot use unlock keys on iOS: availability isATTESTATION_REQUIRED. - A sign-out keeps the key, because signing in again after one is what it is for. To forget a worker
on the phone, call
disableUnlockKey()and thenlogout(). Session.amrtells you how the session began (["hwk","uv"]after an unlock key), and aUnlockKeyChangedevent fires when a key is registered or forgotten. Awhenover everyFieldEventin Kotlin, or aswitchin Swift, needs the new case.
The worker’s own photo
Section titled “The worker’s own photo”If photos are on for the client, the session’s worker carries photoVersion (null when there is no
photo, or photos are off) and canSetOwnPhoto (true only when the client’s policy lets workers set their
own and the session is the worker’s own). A photo changed elsewhere shows as a new photoVersion at the
next sign-in or refresh, with the session-changed event; there is no separate photo event.
const photo = await auth.getPhoto({ size: "thumb", haveVersion: held }); // null: none; photo.notModified: keep yoursif (auth.session!.worker.canSetOwnPhoto) { await auth.setPhoto({ bytes, contentType: "image/jpeg" }); // JPEG, PNG or WebP, decided from the bytes await auth.removePhoto();}val me = (session.state.value as FieldState.SignedIn).sessionval photo = session.getPhoto(PhotoSize.THUMB, haveVersion = held) // null: none; photo.notModified: keep yoursif (me.worker.canSetOwnPhoto) { session.setPhoto(bytes, "image/jpeg") session.removePhoto()}// me: the Session that login returned, or any Session from the statelet photo = try await field.getPhoto(size: .thumb, haveVersion: held)if me.worker.canSetOwnPhoto { try await field.setPhoto(jpegData, contentType: "image/jpeg") try await field.removePhoto()}const photo = await field.getPhoto({ size: "thumb", haveVersion: held });if (field.session?.worker.canSetOwnPhoto) { await field.setPhoto({ bytes, contentType: "image/jpeg" }); await field.removePhoto();}A worker can always read their own photo while photos are on, including while a supervisor acts as them,
but cannot change it then (IMPERSONATING). Refusals are OWN_PHOTO_NOT_ALLOWED, PHOTOS_DISABLED,
PHOTOS_DISABLED_FOR_CLIENT, PHOTO_EMPTY, PHOTO_TOO_LARGE (the platform accepts 10 MiB by default),
PHOTO_UNSUPPORTED_TYPE, PHOTO_TYPE_MISMATCH, PHOTO_DIMENSIONS_TOO_LARGE, PHOTO_UNREADABLE,
PHOTO_BUSY and TOO_MANY_REQUESTS with a retry delay. The photo is another worker’s to see only through
your own backend; the device route returns the signed-in worker’s photo only.
Supervisors and sign-in codes
Section titled “Supervisors and sign-in codes”A worker marked as able to impersonate can take over for another worker of the same client by typing
their own PIN again, and an administrator can issue a one-time code from the console. Both give a
token whose subject is the worker and whose act claim names who is really acting. See
Impersonation for the administrator side.
await auth.actAs({ workerCode: "W002", pin: supervisorPin }); // supervisor's own PINawait auth.endImpersonation(); // restores the supervisor's session
await auth.redeemSignInCode(code); // a code from the console: "FWS1..."The Kotlin and React Native equivalents are actAs(ActAsTarget(workerCode = ..., pin = ...)),
endImpersonation() and redeemSignInCode(code). The supervisor’s own session is kept aside and
restored afterwards; impersonation does not nest, and an impersonated session has its own cap (four
hours by default, impersonationMaxSecs).
Call your backend
Section titled “Call your backend”Every request to your backend carries Authorization: DPoP <access token> and a DPoP proof signed
by the device key, bound to the method and URL. Use the library’s fetch:
const res = await auth.fetch("https://api.example.com/api/gates/open", { method: "POST" });fetch refreshes first when the access token expires within 30 seconds, adds the cached
DPoP-Nonce of that origin, and retries once on 401 WWW-Authenticate: DPoP error="use_dpop_nonce".
val http = OkHttpClient.Builder().addInterceptor(session.interceptor()).build()// or, for other uploaders:val h = session.headersFor("POST", url) // Authorization + DPoP; refreshes first if needed// on 401 use_dpop_nonce: session.headersForRetry("POST", url, response.header("DPoP-Nonce")!!)The interceptor blocks the calling thread (OkHttp’s own), so do not call execute or enqueue from
the main thread. Requests with one-shot bodies are not retried.
const res = await field.fetch("https://api.example.com/trips", { method: "POST", body });const h = await field.headersFor("GET", url); // { Authorization, DPoP } for SSE or upload librariesThe proof is bound to one method and URL and one nonce, so it cannot be reused. For an offline queue, store the request unsigned and sign it at send time.
Your backend verifies all of this: Verify field tokens in your backend.
Sign out
Section titled “Sign out”await auth.logout(); // ends this login familyawait auth.logout({ scope: "device-all" }); // every session on this deviceUse device-all to hand a shared handheld to the next worker. It needs an enrolled device (on a
device that is not enrolled it is 400 INVALID_REQUEST); the plain session scope works anywhere.