Skip to main content

Authentication

The REST API authenticates every request with an OAuth2 / OIDC access token (a Bearer JWT) issued by our identity provider (Keycloak). There are no API keys: server-to-server integrations authenticate as a service account with a client ID and secret and obtain the same kind of token.

Using an access token​

Include the token in the Authorization header on every request:

curl -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
https://api.tourfold.com/api/v2/areas

Requests without a valid token receive 401 Unauthorized β€” see Error responses for the payload and the retry rules.

Obtaining access tokens​

Tokens are issued by the workspace's Keycloak realm: tourfold-tenants for most workspaces, or a dedicated realm named tf-<workspace id>. The realm's endpoints are discoverable at:

https://auth.tourfold.com/realms/tourfold-tenants/.well-known/openid-configuration
  1. Redirect the user to the authorization endpoint:
https://auth.tourfold.com/realms/tourfold-tenants/protocol/openid-connect/auth
?client_id=YOUR_CLIENT_ID
&response_type=code
&redirect_uri=YOUR_REDIRECT_URI
&scope=openid profile email
&state=YOUR_STATE_VALUE
  1. Exchange the authorization code for tokens:
curl -X POST https://auth.tourfold.com/realms/tourfold-tenants/protocol/openid-connect/token \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "grant_type=authorization_code" \
-d "client_id=YOUR_CLIENT_ID" \
-d "client_secret=YOUR_CLIENT_SECRET" \
-d "code=AUTHORIZATION_CODE" \
-d "redirect_uri=YOUR_REDIRECT_URI"

Response:

{
"access_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...",
"token_type": "Bearer",
"expires_in": 300,
"refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"id_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9..."
}

Service accounts (server-to-server)​

Background jobs and other systems authenticate as a service account: an integration identity that receives its grants from its roles, like a user, but never signs in interactively. A service account authenticates with a client ID and client secret (the client_credentials grant, RFC 6749 Β§4.4). Tourfold shows the secret only once: when the account is created or its secret is rotated.

1. Create the service account​

A workspace admin creates it in Settings β†’ Users & roles β†’ Service accounts, or with POST /api/v2/service-accounts (requires the service-accounts:manage grant, which only the Owner and Admin roles carry), passing a name, an optional description and the roles. Only a human user can create a service account, rotate its secret, activate it, or re-allow one of its legacy tokens; a service account calling these operations gets 403 with data.reason: wrong_actor_type, whatever its grants. A compromised integration therefore cannot mint a second credential that outlives its deactivation. The response carries everything the integration needs:

FieldUse
client_idthe client ID (tf-sa-<service account id>)
client_secretthe client secret. Returned only in this response: store it in a secrets manager right away. Reading the account later never returns it.
token_endpointwhere to request tokens

Always copy token_endpoint from the response rather than building it: the realm depends on the workspace (see Enterprise: dedicated realm). See the Service accounts operations in the OpenAPI reference.

2. Request a token​

Post the client_credentials grant to token_endpoint, authenticating with the client ID and secret over HTTP Basic (client_secret_basic):

curl -X POST "$TOKEN_ENDPOINT" \
-u "$CLIENT_ID:$CLIENT_SECRET" \
-d "grant_type=client_credentials"
import os
import requests # pip install requests

TOKEN_ENDPOINT = "https://auth.tourfold.com/realms/tf-<workspace id>/protocol/openid-connect/token"
CLIENT_ID = "tf-sa-<service account id>"
CLIENT_SECRET = os.environ["TOURFOLD_CLIENT_SECRET"]

def request_token() -> str:
response = requests.post(
TOKEN_ENDPOINT,
auth=(CLIENT_ID, CLIENT_SECRET),
data={"grant_type": "client_credentials"},
)
response.raise_for_status()
return response.json()["access_token"]

Sending client_id and client_secret as form fields (client_secret_post) works too. A wrong or rotated secret is refused with 401 and "error": "unauthorized_client". Most OAuth libraries support the client credentials grant directly, for example Spring Security, openid-client (Node.js), Authlib (Python) and Duende IdentityModel (.NET).

3. Use and renew tokens​

An access token is valid for 5 minutes; there is no refresh token. Request a new token before exp, and after any 401 β€” not only before exp. Several changes end the tokens a service account already holds (next section), and requesting a fresh token is the recovery for all of them.

Rotating the secret​

POST /api/v2/service-accounts/{service_account_id}/rotate-secret (or Rotate secret in the settings) returns a new client_secret, once. The previous secret stops working immediately; there is no overlap period, so update the integration right after rotating.

Rotating the secret, deactivating the account or deleting it ends every token issued before the change within 30 seconds. Expect one 401 on the current token, then request a new token with the new secret. A token requested within the same second as the change can also be refused once; the next request succeeds.

Lost or leaked secret​

Rotate the secret, or deactivate the service account (POST /api/v2/service-accounts/{service_account_id}/deactivate). Either takes effect within 30 seconds. Deleting the account has the same effect and cannot be undone.

Device enrollment (pairing secret)​

Two device-enrollment operations are called by a freshly provisioned device that holds no token of any kind yet: POST /api/v2/devices/{device_id}/enroll and POST /api/v2/devices/{device_id}/enroll/challenge. They authenticate with the one-time pairing secret delivered in the device-setup link (QR code, SMS, or email) instead of a bearer token:

  • the pairing secret travels in the request body (secret), never in a header or URL;
  • the workspace is named by the X-Tenant-Id header, since without a token there is no workspace context to derive.

The secret is short-lived and bound to one device; enrollment succeeds at most once per device. After enrolling, the device holds its own confidential client and obtains tokens via the standard client-credentials flow (private_key_jwt) β€” the pairing secret plays no further role. All other device endpoints use normal bearer authentication.

Pairing answers 403 tenant-disabled for a disabled workspace and 402 tenant-billing-locked for a billing-locked one; the refusal does not use up the setup link, which pairs the device once the workspace is usable again, as long as it has not expired.

If the app loses its key (reinstalled, wiped, or replaced device), an admin resets the enrollment with POST /api/v2/devices/{device_id}/reset-enrollment and sends a new setup link. The reset signs the installed app out at once and voids every setup link generated before it; the device keeps its id, Vehicle association, and history.

Device proof next to a user token (X-Device-Authorization)​

Current-Device self-service uses /api/v2/devices/current. Current means the Device proven by this request; it never means the person's most recently used Device. A person can have independent logins on several Devices.

Human requests carry the user's token in Authorization and the Device's bearer token in X-Device-Authorization: Bearer <device token>. The secondary token is verified for signature, issuer and workspace without becoming the request's principal. A missing proof returns 403 devices/device-token-required with data.reason: device_proof_missing. A malformed, unverifiable, disabled or deleted Device proof returns 403 devices/device-token-invalid with device_proof_invalid; a proof for another workspace uses tenant_scope, and a verified non-Device principal or unsupported Device kind uses wrong_actor_type. These are secondary-proof failures: refreshing the human access token does not resolve them.

OperationPurpose
POST /api/v2/devices/current/user-associationRegister a fresh human login; returns 201 with an episode id and Location.
GET /api/v2/devices/current/user-associationRecover this exact human session's current episode after restarting the app or losing a registration response. A different person or independent session's login is concealed as 404.
POST /api/v2/devices/current/user-association/endSend expected_user_association_id to end only that episode. Returns 200 CurrentDeviceContext; a newer owned episode returns 409 devices/user-association-changed. A foreign session returns 409 devices/current-user-association-required before the episode is compared.
GET /api/v2/devices/current/vehicle-associationRead the Device's association identity, mode and source flags with human plus Device proof, or a Device primary token. A foreign human login is concealed as 404.
POST /api/v2/devices/current/vehicle-association/endSend expected_vehicle_association_id to disconnect with self-service permission. Human login and Tour assignments remain.
POST /api/v2/devices/current/logoutUse the Device token as primary bearer and send both expected_vehicle_association_id and expected_user_association_id (explicit null for absence). Ends the matching context atomically.

Commands that require a registered human login return 409 devices/current-user-association-required when valid human and Device proof do not match the registered session. Register that login before retrying; more grants do not bypass registration. Ending an already absent human login remains an idempotent success. A human token on the Device-only /logout operation returns 403 devices/device-token-required with wrong_actor_type, even if a secondary Device token is supplied.

PATCH /api/v2/vehicle-device-associations/{association_id} has two authorization alternatives:

  • Management requires both vehicles:update and devices:update; no secondary proof is needed.
  • Current-Device source selection requires vehicles:device-location:use-self, the matching registered human session and secondary Device proof, plus authority on a readable active Tour using the Vehicle. Send only is_location_source and optional lock_version. This path needs no vehicles:read grant and returns only the caller's association and source flags; it does not permit association list/detail reads, changes to another Device, or management of mode/preference.

Registration creates a new episode even for the same person. Recover an uncertain registration with GET before trying a new registration. Logout retries must retain their original episode IDs; a newer episode must never be adopted just to complete an older logout. Device logout keeps enrollment; clear local Device credentials only after the backend acknowledges cleanup. The three end/logout commands return 200 with the final CurrentDeviceContext from their transaction. Human logout can revoke the caller immediately, so use that returned state instead of requiring a follow-up human GET. For an unknown outcome, Device-primary context reads remain available for safe recovery.

For an OIDC human login, registration binds the verified token session to that Device. A session already bound elsewhere returns 409 resource-conflict; sign in with an independent session on that installation. Ending the human login revokes its session at Tourfold, including subsequently refreshed tokens. Requests return 401 authentication-required with data.reason=token_invalid, even without the secondary header. Other independent sessions remain usable. Human logout retains Device credentials and its Vehicle association. Local revocation also queues provider-session cleanup for the exclusively bound session; it does not sign out the person’s other independent sessions. Enrollment reset also deprovisions Device credentials.

Tour Start accepts the same secondary proof together with device_context and its observed Vehicle-association ID. The context stays at the top level, whether or not vehicle_use selects a Vehicle. Ad-hoc Start follows the same shape. Active use-vehicle takes top-level vehicle_id and optional replace_vehicle_id / add alongside that context. Supplying the secondary header without context returns field-level 422; context without valid proof returns 403. Dispatcher Start without Device context needs no secondary header. The backend coordinates participant cleanup and Vehicle use within Start; a frontend must not implement that invariant as a sequence of disconnect calls.

Whether the mobile app authenticates through its enrolled device at all is a workspace setting, admin-managed devices (admin_managed_devices via GET/PATCH /api/v2/devices/settings, also surfaced pre-login as x_tourfold_admin_managed_devices in the public frontend configuration). When it is off, the app uses the standard user login from any device and enrolls itself in the background.

What a device token can call​

A device token, obtained with the client-credentials flow above, only reaches what a device does for itself. Grants on the token never widen this.

OperationPurpose
POST /device-intake/v1/tourfold/devices/{device_id}Send the device's location and telemetry.
GET /device-intake/v1/tourfold/devices/{device_id}/location-policyRead the device's location policy.
GET /api/v2/devices/{device_id}, GET /api/v2/devices/{device_id}/current-state, GET /api/v2/devices/{device_id}/enrollmentRead the device's own record. These also need the devices:read grant; device tokens currently carry no grants.
Plugin operations documented for a device tokenFor example, a plugin's driver sign-in on the device.
  • An operation with {device_id} in the path accepts only the calling device. Another device's id answers 403 access-denied with data.reason: not_owner.
  • Every other operation answers 403 access-denied with data.reason: wrong_actor_type.
  • Operations that need no token are not affected.

A person who signs in on a device, for example a driver after the device login, gets a user token and is authorized like any other user.

Scopes and authorization​

Request the standard OIDC scopes when authenticating:

  • openid β€” required for OIDC compliance
  • profile β€” access to basic profile claims
  • email β€” access to the email claim

Access to individual resources is governed by the caller's workspace roles and grants, not by OAuth scopes. The token identifies who you are and which workspace you act in; what you may read or write is decided by that identity's role assignments. A token that is valid but lacks the required grant receives 403 Forbidden, with the missing grant named in data.required_grants where it is statically known.

Object and record grants and per-type access​

Record reads require objects:records:read; create, update, and delete use their matching objects:records:* grants. Read access is independent, so a read-only integration does not need a write grant.

Object definitions are tenant-visible metadata. GET /api/v2/definitions/objects returns the stable object catalog; a per-type ACL does not hide the object definition. Trying to read denied record data returns 403 access-denied with data.reason: not_member.

Token management​

Refreshing an access token​

Access tokens are short-lived. Use the refresh token to obtain a new one:

curl -X POST https://auth.tourfold.com/realms/tourfold-tenants/protocol/openid-connect/token \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "grant_type=refresh_token" \
-d "client_id=YOUR_CLIENT_ID" \
-d "client_secret=YOUR_CLIENT_SECRET" \
-d "refresh_token=YOUR_REFRESH_TOKEN"

Revoking a session​

curl -X POST https://auth.tourfold.com/realms/tourfold-tenants/protocol/openid-connect/logout \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "client_id=YOUR_CLIENT_ID" \
-d "client_secret=YOUR_CLIENT_SECRET" \
-d "refresh_token=YOUR_REFRESH_TOKEN"

Security best practices​

  • Store tokens, client secrets and private keys securely β€” environment variables or a secrets manager, never in version control. A service account's client secret is shown only once; rotate it if it may have leaked.
  • Handle expiry β€” implement refresh-token logic for long-running applications; service accounts request a new token before exp and after any 401.
  • Use HTTPS only β€” never send tokens over unencrypted connections.
  • Request only the scopes you need.
  • Use a distinct client per environment β€” separate clients/credentials for development, staging, and production.

Enterprise: dedicated realm​

By default all workspaces authenticate against the shared tourfold-tenants realm. Enterprise workspaces can be provisioned with their own dedicated Keycloak realm β€” for example to bring their own identity provider / SSO, custom password and session policies, or isolated user federation. When a dedicated realm is in use, the tourfold-tenants segment in the endpoints above is replaced by the workspace's realm name, tf-<workspace id>. A service account's token_endpoint always names the right realm. Contact support to arrange a dedicated realm.

Error responses​

Authentication and authorization failures are RFC 9457 problem documents served as application/problem+json, exactly like every other API error. Two statuses are relevant:

  • 401 Unauthorized β€” the request carried no usable identity. Obtaining or refreshing credentials is what fixes it.
  • 403 Forbidden β€” the request is authenticated, but that identity is not permitted to perform the action. Recovery depends on data.reason: missing grants can be granted, while ownership, membership, and self-target restrictions require a change in the caller/resource relationship.

Both carry a machine-readable data.reason so a client can decide what to do next without parsing human-readable detail prose.

The authorization vocabulary below applies to access-denied and narrower authorization-denial types. A type-specific 403 may define its own reason value; the existing tenant-disabled problem is documented below as the explicit example.

note

Treat data as optional β€” never dereference data.reason without a presence check. data.reason is always present on 401 and on authorization-denial 403 responses; data.required_grants only when the denial is grant-based and the required grants are statically known (a check implemented as a custom rule rather than a grant cannot name one).

401 β€” not authenticated​

Returned when the Authorization header is absent, or the token is expired, malformed, issued by an untrusted issuer, or belongs to a session that has ended:

{
"type": "https://problems.tourfold.com/authentication-required",
"title": "Authentication required",
"status": 401,
"detail": "Valid authentication credentials are required",
"data": {
"reason": "token_expired"
}
}

The problem type stays authentication-required for all three causes β€” the cause is carried in data.reason, not in a separate type URI:

data.reasonCauseWhat the client should do
token_missingNo credentials were presented at all.Authenticate using one of the flows above. Retrying the request unchanged fails identically.
token_expiredA well-formed token that is past its expiry.Refresh the access token and replay the request once. This is the only reason that warrants an automatic retry.
token_invalidMalformed token, bad signature, an untrusted issuer, an issuer realm that no longer exists, or a Tourfold login session that has ended through provider logout or local Device-bound revocation.Do not blind-retry β€” the same token keeps failing. Discard the session credentials, resolve the workspace's current authentication configuration, and authenticate again.

Every 401 also carries a WWW-Authenticate header:

  • A token was presented but rejected β†’ the challenge includes the RFC 6750 error parameters, for example WWW-Authenticate: Bearer error="invalid_token", error_description="...".
  • No token was sent β†’ a bare WWW-Authenticate: Bearer.

One other problem type maps to 401: https://problems.tourfold.com/login-failed ("Login failed"). It covers a rejected credential-based login, not an absent or unusable bearer token.

Implementing token refresh​

The reason vocabulary maps directly onto a refresh loop:

  1. 401 with data.reason = token_expired β†’ exchange the refresh token for a new access token, then replay the original request once.
  2. 401 with data.reason = token_missing β†’ no credentials reached the API. Fix the client and authenticate.
  3. 401 with data.reason = token_invalid β†’ stop. Drop the cached token and start a fresh authentication; retrying is guaranteed to fail and only consumes rate-limit budget.
  4. The refresh call itself fails β†’ the refresh token is expired or revoked; re-run the full authorization flow.

An open app event stream can also receive a terminal session notification:

event: SESSION_ENDED:V1
data: {"kind":"SESSION_ENDED:V1"}

It has no replay cursor or user/Device identifiers. Clear the human login and stop reconnecting with its tokens; retain Device enrollment and credentials. Delivery is best effort: reconnect or the next API request enforces a missed revocation with the canonical token_invalid response. A network disconnect alone does not mean the user session ended.

403 β€” authenticated but not permitted​

Returned when the caller is known but is not allowed to perform the action:

{
"type": "https://problems.tourfold.com/access-denied",
"title": "Access denied",
"status": 403,
"detail": "You don't have permission to perform this action",
"data": {
"reason": "missing_grant",
"required_grants": ["users:update"]
}
}

For access-denied and narrower authorization-denial types, data.reason is one of:

data.reasonMeaning
missing_grantThe caller lacks one of the grants the operation requires.
not_ownerThe caller is not the owner of the target resource.
not_authorThe caller did not author the target resource.
not_memberThe caller is not a member of the group the resource belongs to, or of a role allowed to assign the requested role.
plan_restrictedThe workspace's plan or feature flags do not include this capability.
tenant_scopeThe resource belongs to a different workspace than the caller's.
device_proof_missingRequired secondary Device proof was not supplied.
device_proof_invalidSecondary Device proof is malformed, unverifiable, disabled or no longer usable.
self_targetThe operation forbids the caller from targeting themselves. More grants cannot bypass this restriction.
resource_lockedA lock held by another actor prevents this caller from acting. State that prevents every caller from acting is reported as a domain-specific 409 or 422.
wrong_actor_typeThe caller is authenticated as the wrong kind of principal for the operation, for example a device token where a user is required, a user token where the device itself must call, or a service account creating service accounts or rotating their secrets. More grants cannot bypass this.

A deactivated workspace is reported as the type-specific https://problems.tourfold.com/tenant-disabled problem with data.reason = TENANT_INACTIVE. Branch on type before interpreting type-specific data; do not treat TENANT_INACTIVE as an additional value in the closed authorization-denial list.

data.required_grants lists the grants involved in the check, not necessarily alternatives. An operation may require all listed grants, any one of them, or a documented combination; consult its authorization requirements rather than inferring boolean logic from this flat list. It is present only when the denial is grant-based and the required grants are statically known, so clients must treat it as optional. Treat grant values as opaque identifiers from the grant catalog. Existing values include users:read and schemas:write; newer grants use camelCase, for example tasks:read and tasks:write. Do not infer or transform a grant's spelling.

Retrying a 403 never helps on its own: either the caller needs a role that carries the missing grant, or the action is unavailable for that resource.

The internal admin control plane (admin-v1) is intentionally thinner. It authenticates callers and returns 401 in exactly the shape above, but it has no per-grant authorization model, so it does not produce per-grant 403s.

Most workspace-scoped operations also pass through tenant-state guards. A deactivated workspace returns 403 tenant-disabled; a billing-locked workspace returns 402 tenant-billing-locked. Billing portal, payment-method, and billing recheck operations remain available so the workspace can recover. These are workspace-state failures rather than token-authentication failures.

A user who is deactivated in a workspace keeps a valid login, because one login can belong to several workspaces. Their token is therefore not rejected as 401: every request to that workspace answers the type-specific https://problems.tourfold.com/user-deactivated problem, with the workspace in data.tenant_id:

{
"type": "https://problems.tourfold.com/user-deactivated",
"title": "User deactivated",
"status": 403,
"detail": "This user account is deactivated in this workspace",
"data": {
"tenant_id": "5f0c6a8e-3c1b-4d2a-9e7f-1a2b3c4d5e6f"
}
}

Do not refresh the token or sign in again on this response; both yield a token that is refused the same way. A workspace administrator has to activate the user again. A user unknown to the workspace, or deleted from it, still gets 401 authentication-required.

Branch on type and status, not on detail​

A feature may return a more specific namespaced problem type in place of the generic access-denied β€” for example https://problems.tourfold.com/comments/cannot-edit-others. The status is still 403 and data.reason still carries the coarse machine-readable cause, so code written against status plus data.reason keeps working while a client that needs the precise case can match the narrower type.

type URIs and HTTP statuses are stable contract. title and detail are human-readable and may be reworded or localized at any time β€” never branch on them.

See Errors for the full problem+json format and the error types reference for the complete type catalog.

Rate limiting​

Authentication is subject to rate limiting. See Rate limiting for details.

Next steps​