Skip to content

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.

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 any

In a React Native app with native screens use FieldClient from @flowcatalyst/field-react-native instead (see the Kotlin and React Native examples below).

clientIdentifier 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.

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 (requireEnrolledDevice in the field policy), where an unknown key is refused as UNKNOWN_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 too
const device = await auth.enrol(scannedText, { label: "Depot 3 scanner" });
// device = { deviceId, mode, clientId, appCodes, platformUrl }, stored under "fc.field.device"

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.

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);
}
});

<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.

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.

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 session

The 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).

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.

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());

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.

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 started
session.keepAlive(false) // trip ended

The 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.

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: true to FieldAuth. The refresh token is then stored behind the biometric (through the native bridge store) and auth.unlock() reads it and refreshes. If the phone’s biometrics changed (KEY_INVALIDATED, raised as BIOMETRIC_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 UnlockPolicy the state becomes Locked after a cold start or time in the background, and the UI calls unlock(activity, "Unlock") (Kotlin) or field.unlock("Unlock") (React Native). Locked never blocks signed requests or keepAlive.

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 computes unlockKeyAvailability() 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() is null, enableUnlockKey() and loginWithUnlockKey() reject with UNLOCK_KEYS_UNSUPPORTED, and disableUnlockKey() 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 open
if (session.unlockKeyAvailability() == UnlockKeyAvailability.AVAILABLE && workerSaysYes()) {
session.enableUnlockKey(activity, UnlockKeyPrompt(title = "Use your fingerprint to sign in", cancel = "Not now"))
}
// on the sign-in screen
try {
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 out

Things to handle:

  • unlockKeyAvailability() answers AVAILABLE, 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_REQUIRED and UNSUPPORTED.
  • Failures keep or drop the key. UNLOCK_KEY_INVALID, UNLOCK_KEY_INVALIDATED (the phone’s biometrics changed), UNLOCK_KEYS_DISABLED and a revoked device delete the local key; PIN_REAUTH_REQUIRED, a lock, NETWORK and 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, cancel and an optional subtitle. Face ID needs NSFaceIDUsageDescription.
  • iOS cannot attest a key. A client whose policy sets unlock key attestation to REQUIRED cannot use unlock keys on iOS: availability is ATTESTATION_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 then logout().
  • Session.amr tells you how the session began (["hwk","uv"] after an unlock key), and a UnlockKeyChanged event fires when a key is registered or forgotten. A when over every FieldEvent in Kotlin, or a switch in Swift, needs the new case.

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 yours
if (auth.session!.worker.canSetOwnPhoto) {
await auth.setPhoto({ bytes, contentType: "image/jpeg" }); // JPEG, PNG or WebP, decided from the bytes
await auth.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.

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 PIN
await 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).

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".

The 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.

await auth.logout(); // ends this login family
await auth.logout({ scope: "device-all" }); // every session on this device

Use 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.