> For the complete documentation index, see [llms.txt](https://docs.payments.thalescloud.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.payments.thalescloud.io/classic-push-provisioning/es/guia-del-desarrollador/cifrado-y-autenticacion-de-datos/codigo-de-autorizacion-formato-jwt.md).

# Código de autorización (formato JWT)

El código de autorización es un JSON Web Token (JWT) generado por el emisor. Sigue la [RFC 7519](https://tools.ietf.org/html/rfc7519) especificación y proporciona protección de identidad e integridad para el servidor TSH.

JWT se utiliza ampliamente para gestionar la autorización y propagar la identidad. Para implementaciones, consulte las bibliotecas listadas en [jwt.io](https://jwt.io/#libraries-io).

Un JSON Web Token tiene tres partes: encabezado, declaraciones (claims) y firma. Cada parte es un objeto JSON que está codificado en base64url.

### Parte 1: el encabezado

El encabezado define el algoritmo de firma utilizado para el token.

Estos son los campos y valores compatibles:

| Campo   | Descripción                                                                                                                                                                                                                                                                                                                                                  |
| ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| **typ** | valor estático 'JWT'                                                                                                                                                                                                                                                                                                                                         |
| **alg** | 'RS256' donde RSA 2048 se utiliza para el cálculo de la firma y SHA256 para el hash.                                                                                                                                                                                                                                                                         |
| **kid** | <p>Identificador de la clave utilizada para la firma del JWT.<br>Se comparte durante el proceso de incorporación entre el emisor y el servidor TSH.<br>RFU para la gestión de la rotación de claves. Valor que básicamente puede ser cualquier valor que desee, siempre que identifique de forma única su clave. Puede ser huella digital, aleatorio ...</p> |

Ejemplo:

```json
// S{ "typ": "JWT", "alg": "RS256" }
```

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

el encabezado (en base64) es:

> `eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9`

### Parte 2: las declaraciones (claims)

El código de autorización contiene declaraciones sobre el usuario autenticado. También define el período de validez del token. Estos son los campos de claim y valores compatibles:

| campo   | descripción                                                                                                                                                                                 |
| ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **iss** | El valor issuerId proporcionado durante el proceso de incorporación.                                                                                                                        |
| **sub** | Deberá ser ya sea el valor issuerCardRefId (ya proporcionado en la carga útil JWE) que identifica el PAN autorizado para la solicitud de provisión push o el tokenId para la operación LCM. |
| **aud** | La 'audiencia' es el solicitante del token, por lo que el tokenRequestorId se proporciona en este campo. valores como: **GOOGLE\_PAY / APPLE\_PAY / SAMSUNG\_PAY**                          |
| **exp** | <p>La fecha de expiración del JWT, el formato de fecha está definido en la especificación RFC 7519.<br>El valor máximo recomendado es la fecha/hora actual + 5 minutos.</p>                 |
| **iat** | El momento en el que se emitió el JWT.                                                                                                                                                      |
| **jti** | <p>El identificador único del JWT.<br>Este es un campo opcional pero si se establece DEBE ser único para cada solicitud.</p>                                                                |

### Parte 3: la firma

La firma se calcula usando RSA-2048 y SHA-256 sobre el encabezado y las declaraciones concatenadas, usando la clave privada del emisor `PRIVATE_KEY`. El servidor TSH valida la firma usando el certificado proporcionado por el emisor durante el proceso de incorporación.

El siguiente ejemplo en Node.js muestra cómo generar un JWT:

```javascript
const jwt = require('jsonwebtoken');
const { v4: uuidv4 } = require('uuid');
const privateKey = fs.readFileSync('private.key');

var JWT = jwt.sign(
  { 
    iss: 'acmebank', 
    sub: panId,
    aud: 'APPLE_PAY',
    exp: Math.floor(Date.now() / 1000) + (2 * 60), // JWT con expiración de 2 minutos
    jti: uuidv4(),
  }, 
  privateKey, 
  { algorithm: 'RS256'}
);
```

Ejemplo de código de autorización:

```
eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJhY21lYmFuayIsInN1YiI6IjEyMyIsImF1ZCI6IkFQUExFX1BBWSIsImp0aSI6IjE4ODU5NTIxLTFmNTQtNGIxNy1hNjA0LWU0MDFmZTAzMjllZCIsImV4cCI6MTcyMzQ3NDIwNywiaWF0IjoxNzIzNDc0MDg3fQ.GGUfe8o8Uw6wl70bnO0tRgrflLAY63gLU_G_ssqBIP6-mQLO0NSgu8OGmKn2fxD91POfSS1W8aifxZMRnFQ721GBwD8UM9eDjXmglHN-l_ILYv4zEgy9ghZ7j0cif9sGObt2Zz35-21SXccK1twtvjrzAODl7XJ4KfFl8VT2OHhwsB2WT6HKYAw1uB8kPc6S3sOqB6eM3NJ6hw6mBCfSOkEp0KXeipiYmChiylCKWSM6Wv3o5YVn9_9oCi1O6Cw7Tk-F9YqU8GtGrFWNfYRL3VbgUPqIqWbzb88hbuZPC485rfiK56TxIJBbqmdQtqBHcoGWAhywCLD4zbOU3viCzQ
```


---

# 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 dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.payments.thalescloud.io/classic-push-provisioning/es/guia-del-desarrollador/cifrado-y-autenticacion-de-datos/codigo-de-autorizacion-formato-jwt.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
