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

# Autenticación

> Inicia sesión y autoriza solicitudes

<Note>
  **Sin claves de API.** 4casters todavía no emite claves de API. Inicia sesión con el nombre de usuario y la contraseña de tu cuenta, exactamente como lo harías en el sitio web, y usa el token devuelto. Consulta la [descripción general de autenticación](/es/pages/authentication) para ver cómo se usa el token en las tres APIs y cómo manejar su vida útil de 30 días.
</Note>

Para usar cualquier ruta autenticada necesitas un token de autenticación. Los tokens se obtienen al iniciar sesión y son válidos durante **30 días**, tras lo cual se requiere un nuevo inicio de sesión.

<h2 id="log-in">
  Iniciar sesión
</h2>

`POST /user/login`

<CodeGroup>
  ```bash curl theme={null}
  curl -X POST https://api.4casters.io/user/login \
    -H "Content-Type: application/json" \
    -d '{"username": "your_username", "password": "your_password"}'
  ```

  ```json JSON body theme={null}
  {
    "username": "your_username",
    "password": "your_password"
  }
  ```
</CodeGroup>

<h3 id="request">
  Solicitud
</h3>

<ParamField body="username" type="string" required>Nombre de usuario de la cuenta (o email).</ParamField>
<ParamField body="password" type="string" required>Contraseña de la cuenta.</ParamField>

<h3 id="response">
  Respuesta
</h3>

El token se devuelve tanto en `data.user.auth` **como** en una cookie `auth` firmada (`Set-Cookie`). En la mayoría de las integraciones de servidor querrás capturar `data.user.auth` y descartar la cookie.

```json theme={null}
{
  "data": {
    "user": {
      "id": "5fe37acbb5a23600123662c1",
      "username": "your_username",
      "auth": "5cd551d6...",
      "type": "p2p",
      "oddsFormat": "american",
      "displayBalance": 1250.50,
      "creditLimit": 500,
      "liability": -125.00,
      "commissionCharged": 0.01,
      "hasMarketMakerAccess": false,
      "isPro": false,
      "createdAt": "2020-12-23T17:14:09.000Z"
    }
  }
}
```

Consulta [`User`](/api-reference/openapi.json) en el esquema OpenAPI para todos los campos.

<h3 id="error-responses">
  Respuestas de error
</h3>

| Estado | Significado |
| - | - |
| `400` | `username` y `password` son obligatorios. |
| `401` | El nombre de usuario o la contraseña es incorrecto. |
| `403` | Cuenta baneada, bloqueada o cerrada. |
| `429` | Se superó el límite de tasa de inicio de sesión. |

<h2 id="authorizing-requests">
  Autorizar solicitudes
</h2>

Pasa el token de `data.user.auth` en cada solicitud posterior. Se aceptan tres formatos de encabezado / payload, en este orden de preferencia:

<Tabs>
  <Tab title="Encabezado Authorization (recomendado)">
    ```bash theme={null}
    curl https://api.4casters.io/user/getMe \
      -H "Authorization: Bearer 5cd551d6..."
    ```

    El prefijo `Bearer ` es opcional: también puedes enviar el token sin prefijo.
  </Tab>

  <Tab title="Cookie">
    La cookie `auth` firmada que establece `/user/login` se honra automáticamente en cada endpoint cuando se reutiliza en el mismo cliente.
  </Tab>

  <Tab title="Campo del cuerpo (solo POST)">
    ```json theme={null}
    { "token": "5cd551d6...", "...": "..." }
    ```

    Se ofrece como respaldo para clientes que no pueden establecer encabezados personalizados con facilidad (p. ej. algunos emisores de webhooks).
  </Tab>
</Tabs>

Si no se proporciona token — o el token es desconocido / está expirado — el servidor responde con `401 InvalidCredentials`.

<h2 id="token-rotation">
  Rotación de token
</h2>

Las solicitudes autenticadas con tokens de más de 30 días rotan automáticamente a un token nuevo. Cuando ocurre, el token nuevo se devuelve en el encabezado de respuesta `X-Auth-Token` (y como cookie `auth` firmada actualizada). El token antiguo deja de funcionar de inmediato; la solicitud que provocó la rotación sigue teniendo éxito, pero cada solicitud posterior con el valor antiguo devuelve `401`. Las integraciones de larga duración deben vigilar este encabezado y persistir el valor nuevo, o simplemente volver a iniciar sesión ante cualquier `401`.

<h2 id="logging-out">
  Cerrar sesión
</h2>

`POST /user/logout` invalida el token usado para hacer la llamada. Las solicitudes posteriores con ese token devuelven `401`; los demás tokens de la misma cuenta no se ven afectados.

<h2 id="two-factor-authentication">
  Autenticación de dos factores
</h2>

La autenticación de dos factores protege los retiros, no el inicio de sesión. `POST /user/login` nunca requiere un código, sea cual sea la configuración de 2FA de la cuenta.


## OpenAPI

````yaml POST /user/login
openapi: 3.1.0
info:
  title: 4casters REST API
  version: 1.0.0
  description: >-
    Public REST API for the 4casters peer-to-peer betting exchange. Use this API
    to manage your account, query the orderbook and games, and place / edit /
    cancel orders.


    All responses (unless noted otherwise) are JSON envelopes of the form `{
    "data": ... }`.
  contact:
    name: 4casters
    url: https://4casters.io
servers:
  - url: https://api.4casters.io
    description: Production
security:
  - bearerAuth: []
tags:
  - name: Authentication
    description: Login and account session management
  - name: User
    description: Read account info, bets, and orders
  - name: Orders
    description: Place, edit, look up, and cancel orders
  - name: Markets
    description: Browse leagues, games, participants, and orderbooks
  - name: Affiliate
    description: Affiliate / referral commission
paths:
  /user/login:
    post:
      tags:
        - Authentication
      summary: Log in
      description: >-
        Initialize a session and obtain an auth token. Auth tokens are valid for
        30 days, after which a fresh login is required. The token returned here
        can also be used to authenticate against the 4casters Streaming
        WebSocket API.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/LoginRequest'
            example:
              username: your_username
              password: your_password
      responses:
        '200':
          description: >-
            Login successful. The auth token is returned both as
            `data.user.auth` and as a signed `auth` cookie.
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: object
                    properties:
                      user:
                        $ref: '#/components/schemas/AuthenticatedUser'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          description: Username or password is incorrect
        '403':
          description: Account banned, locked, or closed
      security: []
components:
  schemas:
    LoginRequest:
      type: object
      required:
        - username
        - password
      properties:
        username:
          type: string
        password:
          type: string
          format: password
    AuthenticatedUser:
      allOf:
        - $ref: '#/components/schemas/User'
        - type: object
          properties:
            auth:
              type: string
              description: >-
                Auth token. Pass as `Authorization: Bearer <auth>` on subsequent
                requests.
            email:
              type: string
              format: email
            passwordSecurityChecks:
              type: object
              description: Result of password strength checks.
    User:
      type: object
      properties:
        id:
          type: string
          description: User id.
        username:
          type: string
        type:
          $ref: '#/components/schemas/UserType'
        oddsFormat:
          $ref: '#/components/schemas/OddsFormat'
        displayBalance:
          type: number
          description: Current balance (display value).
        creditLimit:
          type: number
          description: Credit limit (negative for credit accounts).
        liability:
          type: number
          description: Current open liability across all games.
        commissionCharged:
          type: number
          description: Commission rate charged to this account.
        maxLiability:
          type: number
          description: Account-level cap on liability.
        matchedVolume:
          type: object
          description: Account preferences for displaying matched volume.
        openInterest:
          type: object
          description: Account preferences for displaying open interest.
        isAdmin:
          type: boolean
        hasMarketMakerAccess:
          type: boolean
        isPro:
          type: boolean
        isDeposit:
          type: boolean
        isAlphaUser:
          type: boolean
        sportsbookDefault:
          type: boolean
        defaultRotationNumbers:
          type: boolean
        displayRotationNumbers:
          type: boolean
        viewOddsWithCommission:
          type: boolean
        defaultExpiry:
          type: integer
          nullable: true
          description: Default order expiry, in minutes.
        defaultOffer:
          type: number
          nullable: true
          description: Default offer size when placing orders.
        defaultSendOrderMessage:
          type: boolean
        sportsbookMinimumDisplay:
          type: number
        showChatLastMessage:
          type: boolean
        yesNoSummary:
          type: boolean
        accessCode:
          type: string
          nullable: true
        code:
          type: string
          nullable: true
        p2pCode:
          type: string
          nullable: true
        createdAt:
          type: string
          format: date-time
        emailConfirmation:
          type: boolean
    HttpError:
      type: object
      properties:
        error:
          type: string
          description: Human-readable error message.
    UserType:
      type: string
      enum:
        - free
        - p2p
        - marketmaker
        - agent
      description: Account type.
    OddsFormat:
      type: string
      enum:
        - american
        - decimal
  responses:
    BadRequest:
      description: Bad request
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/HttpError'
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      description: >-
        Pass your auth token in the `Authorization` header. The `Bearer` prefix
        is optional; the server also accepts a signed `auth` cookie or a `token`
        field in the request body.

````

This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.