> ## Documentation Index
> Fetch the complete documentation index at: https://docs.killb.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Autenticación

> Aprende cómo autenticarte con la API de KillB

## Descripción General

La API de KillB usa **JWT (JSON Web Tokens)** para autenticación. Todas las solicitudes API deben incluir un token de acceso válido en el encabezado de Authorization.

<Info>
  La autenticación API usa una combinación de login **email/contraseña** y **API keys** para diferentes patrones de acceso.
</Info>

## Métodos de Autenticación

<Tabs>
  <Tab title="JWT Tokens (Principal)">
    Usado para la mayoría de operaciones API. Obtenido via endpoint de login.

    **Mejor para:** Aplicaciones web y móviles, operaciones específicas de usuario
  </Tab>

  <Tab title="API Keys">
    Usado para operaciones servidor-a-servidor y webhooks.

    **Mejor para:** Servicios backend, operaciones administrativas
  </Tab>
</Tabs>

## Obtener Tus Credenciales

1. **Regístrate** en KillB en [killb.com](https://www.killb.com)
2. **Accede al Dashboard** en [otc.killb.com](https://otc.killb.com)
3. **Obtén Credenciales:**
   * Tu email de login y contraseña
   * Tu API key de la configuración del dashboard

## Flujo de Login

### Paso 1: Generar Token de Acceso

```bash theme={null}
POST /api/v2/auth/login
```

**Solicitud:**

```json theme={null}
{
  "email": "tu-email@ejemplo.com",
  "password": "tu-contraseña"
}
```

**Respuesta:**

```json theme={null}
{
  "accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "expiresIn": 3600000,
  "refreshToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}
```

<CodeGroup>
  ```bash cURL theme={null}
  curl --request POST \
    --url https://sandbox.killb.app/api/v2/auth/login \
    --header 'Content-Type: application/json' \
    --data '{
      "email": "tu-email@ejemplo.com",
      "password": "tu-contraseña"
    }'
  ```

  ```javascript Node.js theme={null}
  const response = await fetch('https://sandbox.killb.app/api/v2/auth/login', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      email: 'tu-email@ejemplo.com',
      password: 'tu-contraseña'
    })
  });

  const data = await response.json();
  const accessToken = data.accessToken;
  ```

  ```python Python theme={null}
  import requests

  response = requests.post(
      'https://sandbox.killb.app/api/v2/auth/login',
      json={
          'email': 'tu-email@ejemplo.com',
          'password': 'tu-contraseña'
      }
  )

  data = response.json()
  access_token = data['accessToken']
  ```

  ```php PHP theme={null}
  <?php
  $ch = curl_init('https://sandbox.killb.app/api/v2/auth/login');
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_POST, true);
  curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
      'email' => 'tu-email@ejemplo.com',
      'password' => 'tu-contraseña'
  ]));
  curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);

  $response = curl_exec($ch);
  $data = json_decode($response, true);
  $accessToken = $data['accessToken'];
  ?>
  ```
</CodeGroup>

### Paso 2: Usar Token de Acceso

Incluye el token de acceso en el encabezado `Authorization` para todas las solicitudes API:

```bash theme={null}
Authorization: Bearer TU_ACCESS_TOKEN
```

## Refrescar Tokens

Los tokens de acceso expiran después de 1 hora. Usa el token de refresh para obtener un nuevo token de acceso:

```bash theme={null}
POST /api/v2/auth/refresh
```

**Solicitud:**

```json theme={null}
{
  "refreshToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}
```

**Respuesta:**

```json theme={null}
{
  "accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "refreshToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "expiresIn": 3600000
}
```

<CodeGroup>
  ```javascript Node.js theme={null}
  async function refreshAccessToken(refreshToken) {
    const response = await fetch('https://sandbox.killb.app/api/v2/auth/refresh', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ refreshToken })
    });

    const data = await response.json();
    return data.accessToken;
  }
  ```

  ```python Python theme={null}
  def refresh_access_token(refresh_token):
      response = requests.post(
          'https://sandbox.killb.app/api/v2/auth/refresh',
          json={'refreshToken': refresh_token}
      )
      data = response.json()
      return data['accessToken']
  ```
</CodeGroup>

<Tip>
  Implementa el refresh automático de tokens en tu aplicación para mantener acceso API ininterrumpido.
</Tip>

## Mejores Prácticas de Seguridad

<AccordionGroup>
  <Accordion title="Almacenar Credenciales de Forma Segura" icon="lock">
    * Nunca hagas commit de credenciales en control de versiones
    * Usa variables de entorno para API keys y tokens
    * Rota las API keys regularmente
    * Usa servicios de gestión de secretos
  </Accordion>

  <Accordion title="Gestión de Tokens" icon="clock">
    * Almacena tokens de forma segura
    * Implementa refresh automático de tokens
    * Limpia tokens al cerrar sesión
    * Establece tiempos de expiración apropiados
  </Accordion>

  <Accordion title="Seguridad de Red" icon="shield">
    * Siempre usa HTTPS para solicitudes API
    * Implementa certificate pinning para apps móviles
    * Valida certificados SSL
    * Usa conexiones de red seguras
  </Accordion>
</AccordionGroup>

## Errores de Autenticación

Respuestas de error comunes de autenticación:

| Código de Estado | Error                | Descripción                              |
| ---------------- | -------------------- | ---------------------------------------- |
| `401`            | No Autorizado        | Token inválido o expirado                |
| `403`            | Prohibido            | Token válido pero permisos insuficientes |
| `400`            | Solicitud Incorrecta | Formato de credenciales inválido         |

**Ejemplo de Respuesta de Error:**

```json theme={null}
{
  "errorCode": "AUTH.0001",
  "message": ["Credenciales inválidas"],
  "statusCode": "401"
}
```

## Probar Autenticación

Usa el ambiente sandbox para probar la autenticación:

**URL Sandbox:** `https://sandbox.killb.app`

<Tip>
  Crea una cuenta de prueba separada para pruebas en sandbox. Las credenciales del sandbox no funcionarán en producción.
</Tip>

## Ejemplo: Flujo de Autenticación Completo

Aquí hay un ejemplo completo gestionando el estado de autenticación:

<CodeGroup>
  ```javascript Node.js theme={null}
  class KillBAuth {
    constructor(email, password) {
      this.email = email;
      this.password = password;
      this.accessToken = null;
      this.refreshToken = null;
      this.baseUrl = 'https://sandbox.killb.app';
    }

    async login() {
      const response = await fetch(`${this.baseUrl}/api/v2/auth/login`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          email: this.email,
          password: this.password
        })
      });

      const data = await response.json();
      this.accessToken = data.accessToken;
      this.refreshToken = data.refreshToken;
      return data;
    }

    async refresh() {
      const response = await fetch(`${this.baseUrl}/api/v2/auth/refresh`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          refreshToken: this.refreshToken
        })
      });

      const data = await response.json();
      this.accessToken = data.accessToken;
      this.refreshToken = data.refreshToken;
      return data;
    }

    getAuthHeaders() {
      return {
        'Authorization': `Bearer ${this.accessToken}`,
        'Content-Type': 'application/json'
      };
    }
  }

  // Uso
  const auth = new KillBAuth('tu-email@ejemplo.com', 'tu-contraseña');
  await auth.login();

  // Hacer solicitud autenticada
  const response = await fetch(`${auth.baseUrl}/api/v2/users`, {
    headers: auth.getAuthHeaders()
  });
  ```

  ```python Python theme={null}
  import requests
  from datetime import datetime, timedelta

  class KillBAuth:
      def __init__(self, email, password):
          self.email = email
          self.password = password
          self.access_token = None
          self.refresh_token = None
          self.expires_at = None
          self.base_url = 'https://sandbox.killb.app'

      def login(self):
          response = requests.post(
              f'{self.base_url}/api/v2/auth/login',
              json={'email': self.email, 'password': self.password}
          )
          data = response.json()
          self.access_token = data['accessToken']
          self.refresh_token = data['refreshToken']
          self.expires_at = datetime.now() + timedelta(milliseconds=data['expiresIn'])
          return data

      def refresh(self):
          response = requests.post(
              f'{self.base_url}/api/v2/auth/refresh',
              json={'refreshToken': self.refresh_token}
          )
          data = response.json()
          self.access_token = data['accessToken']
          self.refresh_token = data['refreshToken']
          self.expires_at = datetime.now() + timedelta(milliseconds=data['expiresIn'])
          return data

      def get_auth_headers(self):
          if datetime.now() >= self.expires_at:
              self.refresh()
          return {'Authorization': f'Bearer {self.access_token}'}

  # Uso
  auth = KillBAuth('tu-email@ejemplo.com', 'tu-contraseña')
  auth.login()

  # Hacer solicitud autenticada
  response = requests.get(
      f'{auth.base_url}/api/v2/users',
      headers=auth.get_auth_headers()
  )
  ```
</CodeGroup>

## Próximos Pasos

<CardGroup cols={2}>
  <Card title="Redes Soportadas" icon="network-wired" href="/es/supported-networks">
    Conoce los métodos de pago y redes blockchain disponibles
  </Card>

  <Card title="Crear tu Primer Usuario" icon="user-plus" href="/es/guides/users/create-user">
    Comienza a construir creando perfiles de usuario
  </Card>
</CardGroup>
