Skip to Content
truemetrics Docs

Driver authentication

Driver authentication

Why the last meter is shown only to your logged-in drivers, how your backend issues a driver token, and how your courier app hands it over with every stop.

The last meter is your data: where your couriers park at your customers’ addresses, which door they use, how they walk. It is shown only to a driver who is logged in to your courier app. For that, your backend gives each driver a driver token at login, and your app hands the token to the truemetrics module or the standalone navigation app with every stop. truemetrics checks the token before it answers with a stop’s last meter.

Nothing built into an app could do this: an app sits on hundreds of phones, and whatever it carries can be copied. The token names a driver, is signed by your backend with a key only your backend holds, and ends after a day at most. Neither the truemetrics app nor the module holds a key or a secret of yours. Without a token no stop shows its last meter.

How it works

Three columns. Your backend makes a key pair once and registers the public half at truemetrics; at login it signs a driver token with the private key. Your courier app keeps the token with the session and hands it over with every stop, together with the id_phone from the truemetrics SDK. The truemetrics module or navigation app then shows the stop's last meter.
From the driver's login to the stop's last meter: your part is 0, 1 and 2

Once: a key pair, the public half registered at truemetrics

You make a P-256 key pair. The private key stays in your backend; the public key goes to truemetrics, which registers it under the ID of the API key your courier app runs the truemetrics SDK with. From then on truemetrics accepts tokens signed with that key for your drivers. See Set up.

At login: your backend signs a driver token

A JWT (ES256) that names your driver (sub), the ID of your SDK key (iss) and truemetrics (aud), and ends at exp, at most 24 hours after it was issued. Your backend returns it with the session, and a fresh one at every shift start. See The token.

With every stop: your app hands the token over

Together with the phone’s device ID in the truemetrics SDK (id_phone), which the SDK in your app already has (see The device ID). Module: NavigationRequest.token and idPhone. Standalone app: the intent extras token and id_phone. See In your app.

The rest is truemetrics’ work: the module or the app sends the token with its request for the stop, and truemetrics checks it and answers with the last meter. Without a token or id_phone, or with a token that is no longer valid (see Lifetime and rotation), the stop is shown without its last meter: destination and building only. The module and the app do not tell your app about it, so keeping the token valid is your app’s job.

The token

A JSON Web Token signed with ES256 (ECDSA on the P-256 curve over SHA-256). Three base64url parts, header, claims and signature, joined with dots.

The header:

{ "alg": "ES256", "typ": "JWT" }

No kid: the iss claim says which public key checks the token.

The claims:

{
  "iss": "a1b2c3d4-0000-4000-8000-000000000000",
  "aud": "truemetrics",
  "sub": "driver-4711",
  "iat": 1796198400,
  "exp": 1796241600,
  "jti": "6f1c2a4e-9b7d-4c2e-8a0f-3d5e7b9c1a2b"
}
ClaimContent
issThe ID of the truemetrics API key your courier app runs the truemetrics SDK with. truemetrics tells you this ID when it registers your public key (see Set up). It is an identifier, not the key itself, and your public key is registered under it. If your apps run the SDK with several API keys, register your public key for each, and sign with the ID of the key the phone’s SDK runs with.
audAlways truemetrics.
subYour driver’s ID, as a string: the same value for the same driver every time, different for different drivers. Any stable identifier of yours works; truemetrics does not need to know who the driver is.
iatWhen the token was issued, Unix seconds, by your server’s clock (kept right with NTP).
expWhen it ends, Unix seconds. At most 24 hours after iat; a token with a longer life is not accepted. Stay a little below 24 hours.
jtiA unique ID per token, for example a UUID.

A token is a secret. Your app keeps it with the session, never in a log, a URL or a crash report.

Make it, in Python

The key pair, once, with OpenSSL. The private key is a file your backend reads, like a database password; the public key is what you send to truemetrics.

openssl ecparam -name prime256v1 -genkey -noout -out truemetrics-token-key.pem      # private: stays in your backend
openssl ec -in truemetrics-token-key.pem -pubout -out truemetrics-token-key.pub.pem  # public: to truemetrics

The token, in your login handler, with PyJWT:

# pip install "pyjwt[crypto]"
import time
import uuid

import jwt

PRIVATE_KEY = open("truemetrics-token-key.pem").read()    # from your secrets store in production
TRUEMETRICS_KEY_ID = "a1b2c3d4-0000-4000-8000-000000000000"  # the ID of your SDK API key, from truemetrics

MAX_LIFETIME_S = 24 * 3600


def truemetrics_driver_token(driver_id: str, lifetime_s: int = 12 * 3600) -> str:
    """A driver token for `driver_id`, valid for `lifetime_s` (at most 24 hours)."""
    lifetime_s = min(lifetime_s, MAX_LIFETIME_S)
    now = int(time.time())
    claims = {
        "iss": TRUEMETRICS_KEY_ID,
        "aud": "truemetrics",
        "sub": driver_id,
        "iat": now,
        "exp": now + lifetime_s,
        "jti": str(uuid.uuid4()),
    }
    return jwt.encode(claims, PRIVATE_KEY, algorithm="ES256")

Your login response then carries it next to your own session, for example:

{
  "session": "…",
  "truemetrics": {
    "token": "eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJhMWIyYzNkNC0wMDAwLTQwMDAtODAwMC0wMDAwMDAwMDAwMDAiLCJhdWQiOiJ0cnVlbWV0cmljcyIsInN1YiI6ImRyaXZlci00NzExIiwiaWF0IjoxNzk2MTk4NDAwLCJleHAiOjE3OTYyNDE2MDAsImp0aSI6IjZmMWMyYTRlLTliN2QtNGMyZS04YTBmLTNkNWU3YjljMWEyYiJ9.PDlqRR7PJ923-bOVuzn4LfRhotwkEsVp_60SFlnQzJLg7WgqdpMXQCZAgt2IJtcNVVg817wbnd29GpptA5bpBA",
    "expires_at": "2026-12-02T20:00:00Z"
  }
}

The shape of your response is yours; expires_at (the token’s exp) saves the app from decoding the token to know when to ask for a new one.

Check your own tokens with the public key before you ship:

PUBLIC_KEY = open("truemetrics-token-key.pub.pem").read()

claims = jwt.decode(token, PUBLIC_KEY, algorithms=["ES256"], audience="truemetrics", issuer=TRUEMETRICS_KEY_ID)
assert claims["exp"] - claims["iat"] <= MAX_LIFETIME_S

How the signature works

For another language, or a JWT library you want to check against: ES256 signs the ASCII text base64url(header) + "." + base64url(claims) with ECDSA (P-256, SHA-256). The signature in the token is the two numbers R and S of the ECDSA signature, each as exactly 32 big-endian bytes, concatenated and base64url-encoded without padding (RFC 7518, 3.4). That is not the DER SEQUENCE most crypto libraries produce: libraries such as OpenSSL, Java’s Signature and Python’s cryptography give DER and have to be converted. Written out, without a JWT library:

# pip install cryptography
import base64
import json

from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives.asymmetric.utils import decode_dss_signature


def b64url(data: bytes) -> str:
    return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii")


def sign_token(claims: dict, private_key_pem: str) -> str:
    key = serialization.load_pem_private_key(private_key_pem.encode(), password=None)
    header = b64url(json.dumps({"alg": "ES256", "typ": "JWT"}, separators=(",", ":")).encode())
    payload = b64url(json.dumps(claims, separators=(",", ":")).encode())
    signing_input = f"{header}.{payload}".encode("ascii")

    der = key.sign(signing_input, ec.ECDSA(hashes.SHA256()))   # DER-encoded SEQUENCE of R and S
    r, s = decode_dss_signature(der)
    signature = b64url(r.to_bytes(32, "big") + s.to_bytes(32, "big"))   # JOSE: R ‖ S, 32 bytes each

    return f"{header}.{payload}.{signature}"

Every JWT library that supports ES256 does this for you (PyJWT, jose, Nimbus, jjwt, jsonwebtoken for Node.js, Microsoft’s System.IdentityModel.Tokens.Jwt). Only ES256 is accepted: not HS256 (a shared secret), not RS256 (RSA).

Lifetime and rotation

A token lives at most 24 hours, and stops working before that when:

  • a newer token of the same driver (sub) was used: the newer one wins, on this phone or another;
  • the truemetrics app was reinstalled or its data cleared, or, with the module, your app was: the token belongs to the installation that used it first;
  • the phone is not one truemetrics knows for your account (id_phone missing, not from the SDK’s status, or of another customer).

The module and the standalone app cannot get a new token and do not report a token that no longer works: the stop simply shows no last meter. The scheme that holds:

  • Issue at every login and every shift start. Your login returns the token with the session, and so does the call that starts the day (loading the tour, for example): a fresh token each time. That also mends a reinstallation or a phone swap since the last one.
  • Keep it with the session. In the app’s secure storage, next to your own session token. Never in shared preferences in plain text, never in a log.
  • Check exp before every handover. The app looks at expires_at before each handover and gets a new token first when it has ended or is about to (say, within the next hour).
  • Sessions longer than 24 hours need a refresh. Many courier apps keep a driver logged in for days or weeks. Then the token has to be rotated without a new login: an endpoint of your backend that issues a fresh token for the logged-in driver (POST /truemetrics-token, authenticated with your own session), called at the shift start and when exp comes near.
  • One token per shift or per day is right. A new token for every stop works, but gains nothing.
  • One sub per driver and installation. The module in your app and the standalone app are two installations: give each its own sub (for example driver-4711 and driver-4711-app).
  • Logout. Drop the token with the session. It ends at exp at the latest anyway.

Your server’s clock issues the token; keep it right with NTP. The phone’s clock does not matter for the token.

Your signing key. To replace it, make a new pair, send truemetrics the new public key, and switch your backend to the new private key once truemetrics confirms. Tokens signed with the old key stop working when truemetrics removes it, so let both overlap by a day. If the private key leaked, tell truemetrics at once.

The device ID

id_phone is the phone’s device ID in the truemetrics SDK your app records with. truemetrics picks your settings by it, and checks with the token that the phone is one of yours. Send it with every stop, with or without a token.

Take it from the SDK’s status, not from getDeviceId() at the moment of the handover: the SDK answers getDeviceId() before truemetrics knows the ID. The ID is known once the SDK reported Initialized (or RecordingInProgress, DelayedStart), after its first request following init, so a brand-new installation needs to have been online once. A small holder, started once after TruemetricsSdk.init:

TruemetricsPhone.kt
object TruemetricsPhone {
    @Volatile var id: String? = null
        private set

    fun watch(scope: CoroutineScope) = scope.launch {
        TruemetricsSdk.getInstance().observeSdkStatus().collect { status ->
            when (status) {
                is Status.Initialized -> id = status.deviceId
                is Status.RecordingInProgress -> id = status.deviceId
                is Status.DelayedStart -> id = status.deviceId
                else -> Unit
            }
        }
    }
}

The ID changes every 30 days and after the app’s data was cleared; the holder follows it. In Flutter or React Native, read it from the truemetrics plugin’s status in the same way.

In your app

What the app does is the same for both options: keep the token from your backend, keep the device ID from the SDK’s status (above), hand both over with every stop.

Two more fields on the NavigationRequest:

val request = NavigationRequest(
    destination = LatLon(stop.lat, stop.lon),
    stops = listOf(NavigationStop(id = stop.addressId)),
    routing = true,
    token = session.truemetricsToken,              // from your backend, see above
    idPhone = TruemetricsPhone.id,                 // the SDK's device ID, see above
)

Set up

Send truemetrics your public key

The PEM file from above, to info@truemetrics.io, with the name of the API key (or keys) your courier app runs the SDK with. truemetrics registers it under that key’s ID, switches the last meter on for your account, and tells you the ID: your iss.

Issue tokens and hand them over

Your backend signs tokens at login and shift start, your app hands them over with id_phone.

Test

A driver with a fresh token sees the last meter of a stop with known data; with the token removed from the handover, or with one past its exp, the same stop shows destination and building only. Then the same driver after a new login, and after the truemetrics app (or, with the module, your app) was reinstalled and a fresh token issued. When a stop with known last-meter data shows none for a driver with a token, write to info@truemetrics.io with the driver’s sub, the id_phone, the time, and which app: truemetrics sees why the token was not accepted.

Let an AI agent do it

Add driver tokens with an AI agent: a copy-paste prompt for your backend and your courier app that implements the key pair, the token at login, the rotation and the handover, step by step with your confirmation.

On this page