> For the complete documentation index, see [llms.txt](https://docs.facephi.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.facephi.com/docs.facephi-en/rest-api/identity-api/identity-api-reference/authentication/authenticate-user-v2.md).

# Authenticate User V2

This service validates both the liveness check and facial authentication. It compares the biometric template, previously validated and stored in the client's data repository during the Onboarding process, with a bestImageToken generated at the time of authentication.

#### Functionality

* **First call**: Sets a unique userId for the user.
* **Authentication**: With each authentication attempt, the userId is sent along with the registered biometric template. This template is compared with the current tokenized image (bestImageToken). If they match and the liveness check passes, the user is successfully authenticated.

{% hint style="info" %}
**Maximum template age at registration.** The client configuration can set a maximum age for the `registeredTemplateRaw`, measured from when it was captured. This is checked only on the first call, when the `userId` is not yet registered. If the template exceeds this time limit, the response returns `serviceResultCode` `-2` and the user is not registered. A subsequent call with the same `userId` and a template within the time limit registers the user. Without this configuration, which is managed by Facephi and requested from the support team, this limit is not applied. This check does not apply to [`updateUserTemplate`](https://docs.facephi.com/docs.facephi-en/rest-api/identity-api/identity-api-reference/authentication/update-user-template.md).
{% endhint %}

### Integration

Requires implementation of the **Selphi Mobile Widget** or the **Selphi Web Widget** to generate the **bestImageToken** and the **biometric template (TemplateRaw)**.

### Endpoint

```
POST /services/authenticateUser/v2
```

### Headers

| Name          | Type   | Required | Description                                                   |
| ------------- | ------ | -------- | ------------------------------------------------------------- |
| **x-api-key** | string | **Yes**  | API key for access authorization.                             |
| **family**    | string | No       | Value: **Authentication**. Required for the tracking service. |

{% hint style="info" %}
All calls to the tracking Endpoints with **Identity Platform** must include the `family`.
{% endhint %}

### Request body

**Content-Type:** `application/json`

#### Parameters

| Parameter               | Type   | Required | Description                                                                                                                                                                           |
| ----------------------- | ------ | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `userId`                | string | **Yes**  | Unique user identifier. It must be persisted and associated with the corresponding biometric template. It must contain at least two digits.                                           |
| `registeredTemplateRaw` | string | **Yes**  | Template generated by the Selphi Widget, encrypted with AES256 and tokenized, and sent in Base64 format. It represents the user's facial pattern with the most detected frontal pose. |
| `image`                 | string | No       | Base64-encoded image obtained from the civil registry. It is required if the registered biometric template (registeredTemplateRaw) is not provided.                                   |
| `bestImageToken`        | string | **Yes**  | Property **tokenized bestImage** generated by the Selphi Widget during authentication.                                                                                                |
| `template`              | string | No       | Biometric template in Base64 format. It is required if the tokenized bestImage (bestImageToken) is not provided.                                                                      |
| `merchantReferenceId`   | string | **Yes**  | Customer reference for each authentication. We recommend that this value not contain sensitive information such as PII (personally identifiable information).                         |
| `tracking`              | object | No       | Object representing the required tracking information.                                                                                                                                |
| `tracking.extraData`    | string | No       | Token generated by the SDK Mobile/Web. It contains tracking information tokenized with the Platform.                                                                                  |
| `tracking.operationId`  | string | No       | Operation identifier generated by the SDK Mobile/Web.                                                                                                                                 |

#### Request example: With a registered biometric template

```json
{
  "userId": "001",
  "registeredTemplateRaw": "BAIBAQFpWLJtBYBymCoRF...",
  "bestImageToken": "BAIBAQIJTHP8obR2r9ALdDtR5lT...",
  "merchantReferenceId": "authenticate-001",
  "tracking": {
    "extraData": "BQABAQG2gBNjuHN...",
    "operationId": "123e4567-e89b-12d3-a456-426614174000"
  }
}
```

#### Request example: With an image from the civil registry

```json
{
  "userId": "001",
  "image": "/9j/4AAQ...",
  "bestImageToken": "BAIBAQIJTHP8obR2r9ALdDtR5lT...",
  "merchantReferenceId": "authenticate-001",
  "tracking": {
    "extraData": "BQABAQG2gBNjuHN...",
    "operationId": "123e4567-e89b-12d3-a456-426614174000"
  }
}
```

{% hint style="warning" %}
**Maximum request size: 6 MB.** Base64-encoded templates and images (`registeredTemplateRaw`, `bestImageToken`, `image` and `template`) count toward this limit together, with approximately 33% overhead compared to the original files (maximum total size of approximately 4.5 MB for the original files). Compressed JPEG images of 1–2 MB each at most are recommended. If the limit is exceeded, the gateway responds `413` without processing the request. See [Request size limit](https://docs.facephi.com/pages/bc7bee9358079d52bafa44ad281828eb424e96fe#l%C3%ADmite-de-tama%C3%B1o-de-la-solicitud).
{% endhint %}

### Responses

#### `200` Success

#### Response parameters

| Parameter                           | Type    | Description                                                                                                                                                     |
| ----------------------------------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `serviceResultCode`                 | integer | Code indicating the **overall result** of the service execution. See [Service Result Code](#service-result-code)                                                |
| `serviceResultLog`                  | string  | Descriptive field for the execution result. Includes details when an error or exception occurs. If successful, it indicates the description of the result code. |
| `serviceFacialSimilarityResult`     | number  | Value indicating the **facial similarity** between registeredTemplateRaw and bestImageToken. **1.0 = 100%**                                                     |
| `serviceFacialAuthenticationLog`    | string  | Descriptive field for the facial authentication result. Includes details when an error or exception occurs in the module.                                       |
| `serviceFacialAuthenticationResult` | integer | Code indicating the **facial authentication result**. See [Service Facial Authentication Result](#service-facial-authentication-result)                         |
| `serviceLivenessResult`             | integer | Code indicating the **passive liveness check result**. See [Service Liveness Result](#service-liveness-result)                                                  |
| `serviceLivenessLog`                | string  | Descriptive field for the passive liveness check result. Includes details when an error or exception occurs.                                                    |
| `merchantReferenceId`               | string  | Reference sent in the request body.                                                                                                                             |
| `registeredTemplateRaw`             | string  | Biometric template registered and returned by the SelphID SDK for use in subsequent authentications.                                                            |
| `timestamp`                         | string  | Response timestamp (UTC) in YYYY-MM-DDThh:mm:ssZ format                                                                                                         |
| `transactionId`                     | string  | Transaction identifier associated with the request processed by the API.                                                                                        |

#### Service Result Code

The `serviceResultCode` indicates the overall result of the service execution:

| serviceResultCode | Description                                                                                                                                                                                                                                                                                                 | HTTP code |
| ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------- |
| 0                 | The service execution was successful; the module processed the request correctly.                                                                                                                                                                                                                           | 200       |
| -2                | The `registeredTemplateRaw` exceeds the maximum age configured for the client, and the user is not registered. `serviceResultLog` is `Invalid faceTemplate (token): Expired`, `serviceFacialSimilarityResult` is `0` and `serviceFacialAuthenticationResult` is `0`. Only on the first call for a `userId`. | 200       |

#### Service Liveness Result

The `serviceLivenessResult` indicates the passive liveness check evaluation result:

| Code | Result                          | Description                                                                                            |
| ---- | ------------------------------- | ------------------------------------------------------------------------------------------------------ |
| 0    | None                            | The liveness check could not be evaluated.                                                             |
| 1    | Spoof                           | DEPRECATED. Use 'NoLive' instead.                                                                      |
| 2    | Uncertain                       | DEPRECATED                                                                                             |
| 3    | Live                            | The subject is assumed to be alive.                                                                    |
| 4    | NoneBecauseBadQuality           | The liveness check could not be evaluated due to poor image quality.                                   |
| 5    | NoneBecauseFaceTooClose         | The liveness check could not be evaluated because the detected faces are too close to the edges.       |
| 6    | NoneBecauseFaceNotFound         | The liveness check could not be evaluated because no faces were detected.                              |
| 7    | NoneBecauseFaceTooSmall         | The liveness check could not be evaluated because the detected faces are too small.                    |
| 8    | NoneBecauseAngleTooLarge        | The liveness check could not be evaluated because the angle between faces exceeds the permitted limit. |
| 9    | NoneBecauseImageDataError       | The liveness check could not be evaluated due to errors in the image format.                           |
| 10   | NoneBecauseInternalError        | The liveness check could not be evaluated due to an internal error.                                    |
| 11   | NoneBecauseImagePreprocessError | The liveness check could not be evaluated due to an error during image preprocessing.                  |
| 12   | NoneBecauseTooManyFaces         | The liveness check could not be evaluated because too many faces were detected in the image.           |
| 13   | NoneBecauseFaceTooCloseToBorder | The liveness check could not be evaluated because the face is too close to the edge.                   |
| 14   | NoneBecauseFaceCropped          | The liveness check could not be evaluated because the face is cropped.                                 |
| 15   | NoneBecauseLicenseError         | The liveness check could not be evaluated due to a license error.                                      |
| 16   | NoneBecauseFaceOccluded         | The liveness check could not be evaluated because the face is occluded.                                |
| 17   | NoLive                          | No liveness was detected.                                                                              |
| 18   | NoneBecauseEyesClosed           | The liveness check could not be evaluated because the person's eyes are closed.                        |

#### Facial Authentication Service Result

The `serviceFacialAuthenticationResult` indicates the result of facial matching operations:

| Code | Result                           | Description                                                                                                                                                                      |
| ---- | -------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 0    | NONE                             | Facial verification could not be performed.                                                                                                                                      |
| 1    | NEGATIVE                         | The process completed successfully. The facial patterns of the faces do not match.                                                                                               |
| 3    | POSITIVE                         | The process completed successfully. The facial patterns of the faces match. The value of `serviceFacialSimilarityResult` indicates the % similarity between the compared images. |
| 4    | NONE BECAUSE POSE EXCEED         | Facial verification could not be performed due to the position of the face.                                                                                                      |
| 5    | NONE BECAUSE INVALID EXTRACTIONS | Facial verification could not be performed due to problems extracting the facial pattern.                                                                                        |

#### Example response

```json
{
  "merchantReferenceId": "82b0084f-ddec-4415-8d2f-b085b42a0155",
  "serviceResultCode": 0,
  "serviceResultLog": "",
  "serviceFacialSimilarityResult": 0.9946970343589783,
  "serviceFacialAuthenticationLog": "Positive",
  "serviceFacialAuthenticationResult": 3,
  "serviceLivenessLog": "Live",
  "serviceLivenessResult": 3,
  "timestamp": "2024-10-29T20:29:24Z",
  "transactionId": "531ecbb1-de3d-4907-a737-0db236674e9a",
  "registeredTemplateRaw": "BAIBAQGo+puJyHjfRD8n..."
}
```

#### `400` Bad Request

```json
{
  "status": 400,
  "title": "Bad Request",
  "detail": "Invalid request.",
  "type": "https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/400",
  "errors": []
}
```

#### `401` Unauthorized

```json
{
  "message": "Unauthorized"
}
```

#### `403` Forbidden

```json
{
  "Message": "User is not authorized to access this resource with an explicit deny"
}
```

#### `413` Payload Too Large

The request exceeds the maximum allowed size. The gateway rejects it **without processing it**: the response does not include `serviceResultCode` or `serviceTransactionId`. See [Request size limit](https://docs.facephi.com/pages/bc7bee9358079d52bafa44ad281828eb424e96fe#l%C3%ADmite-de-tama%C3%B1o-de-la-solicitud).

Request larger than 6 MB and up to 10 MB (`Content-Type: application/json`):

```json
{
  "message": "Request Too Long"
}
```

Request larger than 10 MB (10,485,760 bytes) (`Content-Type: text; charset=utf-8`, plain text, not JSON):

```
HTTP content length exceeded 10485760 bytes.
```

#### `502` Bad Gateway

```json
{
  "status": 502,
  "title": "Bad Gateway",
  "detail": "Server got an invalid response.",
  "type": "https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/502"
}
```

#### `504` Gateway Timeout

```json
{
  "message": "Endpoint request timed out"
}
```
