> ## 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.

# 認證

> 登入併為請求授權

<Note>
  \*\*沒有 API 金鑰。\*\*4casters 目前還不發放 API 金鑰。使用你帳戶的使用者名稱和密碼登入，就像在網站上一樣，然後使用回傳的令牌。令牌如何在三套 API 中使用、以及如何處理它 30 天的有效期，見 [認證概述](/zh-Hant/pages/authentication)。
</Note>

要使用任何需認證的路由，你需要一個認證令牌。令牌透過登入獲取，有效期為 **30 天**，之後需要重新登入。

<h2 id="log-in">
  登入
</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 請求主體 theme={null}
  {
    "username": "your_username",
    "password": "your_password"
  }
  ```
</CodeGroup>

<h3 id="request">
  請求
</h3>

<ParamField body="username" type="string" required>帳戶使用者名稱（或電子郵件）。</ParamField>
<ParamField body="password" type="string" required>帳戶密碼。</ParamField>

<h3 id="response">
  回應
</h3>

令牌會同時作為 `data.user.auth` **以及**簽名 `auth` Cookie（`Set-Cookie`）回傳。對於大多數伺服器端整合，你應捕獲 `data.user.auth` 並丟棄 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"
    }
  }
}
```

全部欄位見 OpenAPI schema 中的 [`User`](/api-reference/openapi.json)。

<h3 id="error-responses">
  錯誤回應
</h3>

| 狀態 | 含義 |
| - | - |
| `400` | `username` 和 `password` 為必填。 |
| `401` | 使用者名稱或密碼不正確。 |
| `403` | 帳戶被封禁、鎖定或已關閉。 |
| `429` | 超出登入速率限制。 |

<h2 id="authorizing-requests">
  為請求授權
</h2>

在後續每個請求中傳遞來自 `data.user.auth` 的令牌。按以下優先順序接受三種請求標頭 / 酬載格式：

<Tabs>
  <Tab title="Authorization 請求標頭（推薦）">
    ```bash theme={null}
    curl https://api.4casters.io/user/getMe \
      -H "Authorization: Bearer 5cd551d6..."
    ```

    `Bearer ` 前綴是可選的 — 直接傳遞裸令牌也可以。
  </Tab>

  <Tab title="Cookie">
    `/user/login` 設定的簽名 `auth` Cookie 在同一用戶端重複使用時，會在每個端點上自動生效。
  </Tab>

  <Tab title="請求主體欄位（僅 POST）">
    ```json theme={null}
    { "token": "5cd551d6...", "...": "..." }
    ```

    作為無法方便設定自定義請求標頭的用戶端（例如某些 webhook 傳送方）的回退方案。
  </Tab>
</Tabs>

如果未提供令牌 — 或令牌未知 / 已過期 — 伺服器回應 `401 InvalidCredentials`。

<h2 id="token-rotation">
  令牌輪換
</h2>

使用超過 30 天的令牌發起的已認證請求會自動輪換為新令牌。發生時，新令牌會在 `X-Auth-Token` 回應標頭中回傳（並作為更新後的簽名 `auth` Cookie）。舊令牌立即失效；觸發輪換的那次請求仍會成功，但之後任何使用舊值的請求都會回傳 `401`。長期執行的整合應監聽此回應標頭並持久化新值，或者乾脆在遇到任何 `401` 時重新登入。

<h2 id="logging-out">
  登出
</h2>

`POST /user/logout` 會使發起該呼叫所用的令牌失效。之後使用該令牌的請求回傳 `401`；同一帳戶持有的其他令牌不受影響。

<h2 id="two-factor-authentication">
  雙重認證
</h2>

雙重認證保護的是提款，而不是登入。無論帳戶的 2FA 設定如何，`POST /user/login` 都不會要求驗證碼。


## 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.