> For the complete documentation index, see [llms.txt](https://docs.caf.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.caf.io/sdk-lite/setup/backend/setup.md).

# Setup

This page walks through the backend integration end to end: from the session token your app needs to start the SDK, to the final liveness result.

![Backend integration flow: session token, capture, signedResponse validation, access token and result](https://2345848357-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FFXOsfB19xW3Mn4Vn5DeD%2Fuploads%2Fgit-blob-642c4ef157a4335301b5e8e9fec7b6c9ef586682%2Fface-liveness-lite-backend-flow.png?alt=media)

## Requirements

| Requirement | Used for      | Description                                                                                                                                                                                                                                                                         |
| ----------- | ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Mobile Key  | Steps 1 and 3 | `client-id` and `client-secret` from the [Trust Platform](https://trust.caf.io/) (**Settings** → **API configurations** → **Mobile Keys**). Used to request the session token and to verify the `signedResponse`. See [Authentication](https://docs.caf.io/caf-sdk/authentication). |
| Application | Steps 4 and 5 | An application from the [Trust Platform](https://trust.caf.io/) (**Settings** → **API configurations** → **Applications**) with OAuth2 credentials (`client_id` and `client_secret`), used to obtain an access token.                                                               |
| Permission  | Step 5        | The scope `v1-faces-liveness-attempts:read` granted to the application.                                                                                                                                                                                                             |

The Trust Platform paths above apply to the US region. For the Brazil region, see [Regions](#regions).

{% hint style="warning" %}
Run every call to Certta from your backend. Never put the Mobile Key `client-secret`, the application `client_secret` or an access token in the app.
{% endhint %}

{% hint style="info" %}
The Mobile Key `client-secret` and the application `client_secret` are different credentials. The first one signs the Authentication Token and verifies the `signedResponse`; the second one obtains the access token to read the result.
{% endhint %}

## Regions

Face Liveness Lite runs in two isolated regions. Pick one and use its hosts in every step.

| Host                          | US                          | Brazil                      |
| ----------------------------- | --------------------------- | --------------------------- |
| Web (session token)           | `https://web.us.prd.caf.io` | `https://web.sa.prd.caf.io` |
| API (access token and result) | `https://api.us.prd.caf.io` | `https://api.sa.prd.caf.io` |

{% hint style="warning" %}
Regions are fully isolated. Nothing created in one region is available in the other:

* **Keys** — use the Mobile Key and the application credentials of the region you call.
* **Product settings** — settings are not replicated between regions.
* **Liveness attempts** — a `livenessAttemptId` created in one region is not found in the other.

All steps of a transaction — session token, capture and result — must happen in the same region.
{% endhint %}

To use the Brazil region, contact Certta. Certta provides the Mobile Key and the application credentials for Brazil.

The SDK selects the region from the session token, so the app needs no region setting. For the minimum SDK versions, see [Regions](https://docs.caf.io/sdk-lite/face-liveness-lite.md#regions).

{% stepper %}
{% step %}

## Request the session token

Your backend signs an Authentication Token with the Mobile Key and exchanges it for a session token. For the full details, see [Authentication](https://docs.caf.io/caf-sdk/authentication).

The Authentication Token is a JWT signed with the Mobile Key `client-secret`, with this payload:

| Claim | Required | Description                                      |
| ----- | -------- | ------------------------------------------------ |
| `iss` | Yes      | The Mobile Key `client-id`.                      |
| `exp` | No       | Expiration time (Unix timestamp). Keep it short. |

```javascript
const jwt = require('jsonwebtoken');

const authenticationToken = jwt.sign({ iss: mobileKeyClientId }, mobileKeyClientSecret, {
  algorithm: 'HS256',
  expiresIn: '10m',
});
```

Send it to the session token endpoint:

|                   |                                                                                  |
| ----------------- | -------------------------------------------------------------------------------- |
| **Base URL**      | `https://web.us.prd.caf.io/bff` (US) or `https://web.sa.prd.caf.io/bff` (Brazil) |
| **Path**          | `GET /session-tokens`                                                            |
| **Authorization** | `Bearer <AUTHENTICATION_TOKEN>`                                                  |

```bash
curl -X GET 'https://web.us.prd.caf.io/bff/session-tokens' \
  -H 'Authorization: Bearer <AUTHENTICATION_TOKEN>'
```

### Response

```json
{
  "requestId": "string",
  "sessionToken": "string",
  "tokenId": "string"
}
```

| Field          | Type   | Description                                                                                            |
| -------------- | ------ | ------------------------------------------------------------------------------------------------------ |
| `requestId`    | String | Identifier of this request. Use it when you contact support.                                           |
| `sessionToken` | String | Token used to start the SDK in the app.                                                                |
| `tokenId`      | String | Identifier of the issued token. **Store it** — you need it to validate the `signedResponse` in step 3. |

Send the `sessionToken` to the app and keep the `tokenId` on your backend, linked to the user's journey. The app passes the `sessionToken` to the SDK as `mobileToken`, together with the `personId`:

| Platform | Where the `sessionToken` goes                                                                                                                           |
| -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
| iOS      | `setup(mobileToken:personId:…)` — see [Starting Liveness Flow](https://docs.caf.io/sdk-lite/setup/ios/configuration/starting-liveness-flow.md)          |
| Android  | `CafLivenessConfig(mobileToken = …)` — see [Starting Liveness Flow](https://docs.caf.io/sdk-lite/setup/android/configuration/starting-liveness-flow.md) |

Request a new session token right before each liveness attempt. Treat each `tokenId` as single-use: your backend accepts only one `signedResponse` for it (see step 3).
{% endstep %}

{% step %}

## Receive the `signedResponse`

When the capture ends, the SDK returns a `signedResponse` to your app, which must forward it to your backend. It is returned on success and on failure:

| Platform | Success                                     | Failure                                                        |
| -------- | ------------------------------------------- | -------------------------------------------------------------- |
| iOS      | `didFinishWithSuccess(livenessResult:)`     | `didFinishWithFailure(type:description:signedResponse:)`       |
| Android  | `LivenessLiteEvent.Success(signedResponse)` | `LivenessLiteEvent.Failure(signedResponse, type, description)` |

The `signedResponse` is a signed JWT. Its payload contains:

```json
{
  "livenessAttemptId": "string",
  "tokenId": "string",
  "sessionId": "string",
  "personId": "string"
}
```

| Field               | Type   | Description                                                                                           |
| ------------------- | ------ | ----------------------------------------------------------------------------------------------------- |
| `livenessAttemptId` | String | Unique identifier of the liveness attempt. Used to retrieve the result in step 5.                     |
| `tokenId`           | String | Identifier of the session token that started this capture. Must match the `tokenId` stored in step 1. |
| `sessionId`         | String | Identifier of the registered liveness session.                                                        |
| `personId`          | String | Identifier of the person associated with the attempt.                                                 |

{% hint style="info" %}
The `signedResponse` does not carry `isAlive` or images. The SDK does not wait for the result either: your backend retrieves it in step 5.
{% endhint %}
{% endstep %}

{% step %}

## Validate the `signedResponse`

Before you use any value from the payload, check:

1. **Signature** — the JWT verifies with your Mobile Key `client-secret`, using only the `HS256` algorithm.
2. **`tokenId`** — it is present and equal to the `tokenId` you stored in step 1.
3. **Single use** — the `tokenId` was not used before. Mark it as used in the same operation as this check, so that two concurrent requests cannot both pass.
4. **`personId`** (optional) — it is equal to the `personId` your app passed to the SDK.

If a check fails, reject the `signedResponse`. See [Error Handling](https://docs.caf.io/sdk-lite/error-handling/backend/error-handling.md#validation-errors). The payload has no `exp` claim: do not require one.

Example in Node.js, with the [`jsonwebtoken`](https://www.npmjs.com/package/jsonwebtoken) library:

```javascript
const jwt = require('jsonwebtoken');

// `session` is the record your backend stored in step 1: { tokenId, personId, used }
function validateSignedResponse(signedResponse, session, mobileKeyClientSecret) {
  const payload = jwt.verify(signedResponse, mobileKeyClientSecret, { algorithms: ['HS256'] });

  if (!payload.tokenId || payload.tokenId !== session.tokenId) {
    throw new Error('tokenId missing or mismatch');
  }

  if (session.used) {
    throw new Error('tokenId already used');
  }

  // Optional
  if (payload.personId !== session.personId) {
    throw new Error('personId mismatch');
  }

  // Persist this in the same atomic operation as the check above
  session.used = true;

  return payload.livenessAttemptId;
}
```

{% endstep %}

{% step %}

## Obtain an access token

The result endpoint uses OAuth2. Exchange the application credentials for an access token:

|                  |                                                                          |
| ---------------- | ------------------------------------------------------------------------ |
| **Base URL**     | `https://api.us.prd.caf.io` (US) or `https://api.sa.prd.caf.io` (Brazil) |
| **Path**         | `POST /oauth2/token`                                                     |
| **Content-Type** | `application/x-www-form-urlencoded`                                      |

| Body field      | Type   | Required | Description                       |
| --------------- | ------ | -------- | --------------------------------- |
| `grant_type`    | String | Yes      | Fixed value: `client_credentials` |
| `client_id`     | String | Yes      | ID of the application             |
| `client_secret` | String | Yes      | Secret of the application         |

Do not send a `scope` parameter. The access token carries the scopes granted to the application.

```bash
curl -X POST 'https://api.us.prd.caf.io/oauth2/token' \
  -H 'Content-Type: application/x-www-form-urlencoded' \
  -d 'grant_type=client_credentials&client_id=<CLIENT_ID>&client_secret=<CLIENT_SECRET>'
```

```json
{
  "access_token": "string",
  "expires_in": 3600,
  "token_type": "Bearer"
}
```

`expires_in` is the token lifetime in seconds. Reuse the token until it expires, then request a new one.
{% endstep %}

{% step %}

## Retrieve the result

|              |                                                                          |
| ------------ | ------------------------------------------------------------------------ |
| **Base URL** | `https://api.us.prd.caf.io` (US) or `https://api.sa.prd.caf.io` (Brazil) |
| **Path**     | `GET /v1/faces/liveness/attempts/{attemptId}/await`                      |

This endpoint waits on the server until the attempt finishes processing and returns the result in a single call. When the result is ready, the response carries a final `status`: `COMPLETED` or `FAILED`. If the result is not ready within the server's wait, the endpoint returns `attempt_not_found`; see [Error Handling](https://docs.caf.io/sdk-lite/error-handling/backend/error-handling.md#result-errors).

### Path parameters

| Parameter   | Type   | Required | Description                                                                |
| ----------- | ------ | -------- | -------------------------------------------------------------------------- |
| `attemptId` | String | Yes      | The `livenessAttemptId` read from the verified `signedResponse` in step 3. |

### Headers

| Header          | Type   | Required | Description                                                                                      |
| --------------- | ------ | -------- | ------------------------------------------------------------------------------------------------ |
| `Authorization` | String | Yes      | `Bearer` access token from step 4, of an application that has `v1-faces-liveness-attempts:read`. |

### Example

```bash
curl -X GET \
  'https://api.us.prd.caf.io/v1/faces/liveness/attempts/<LIVENESS_ATTEMPT_ID>/await' \
  -H 'Authorization: Bearer <ACCESS_TOKEN>'
```

### Timing

* Set your HTTP client timeout above **15 seconds**: the call can wait on the server while the attempt is processed.
* Call the endpoint as soon as your backend has the `livenessAttemptId`. Later calls return the same result, but take longer.

The response fields are described in [Result Reference](https://docs.caf.io/sdk-lite/setup/backend/result-reference.md). To decide what to do with the result, see [Failure Handling](https://docs.caf.io/sdk-lite/failure-handling/backend/failure-handling.md).
{% endstep %}
{% endstepper %}

## Before you go live

* [ ] Every call to Certta runs on your backend, and no secret is in the app. See [Requirements](#requirements).
* [ ] You use the Mobile Key and the application credentials of the region you call, and all steps use the same region. See [Regions](#regions).
* [ ] You verify the `signedResponse` with `HS256`, and the `tokenId` is present, matches and is used only once. See [Validate the `signedResponse`](#validate-the-signedresponse).
* [ ] You approve only from the result endpoint's response, never from what the app reports. See [Failure Handling](https://docs.caf.io/sdk-lite/failure-handling/backend/failure-handling.md).
* [ ] You handle every result in the decision table: live, not live, no usable image and did not finish. See [Deciding on the result](https://docs.caf.io/sdk-lite/failure-handling/backend/failure-handling.md#deciding-on-the-result).
* [ ] You call the result endpoint once more when you get `attempt_not_found`. See [Result errors](https://docs.caf.io/sdk-lite/error-handling/backend/error-handling.md#result-errors).
* [ ] Your HTTP client timeout is above 15 seconds. See [Retrieve the result](#retrieve-the-result).
* [ ] You reuse the access token until it expires. See [Obtain an access token](#obtain-an-access-token).
* [ ] You log the `requestId` (or the `x-amzn-RequestId` response header) for support. See [Contacting support](https://docs.caf.io/sdk-lite/error-handling/backend/error-handling.md#contacting-support).


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.caf.io/sdk-lite/setup/backend/setup.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
