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

# API Key 輪換

> 零停機輪換 ARouter API Key 的最佳實踐。透過定期更換憑證保障應用程式安全。

定期輪換 API Key 可以降低金鑰洩露的影響範圍，並滿足許多安全合規要求。ARouter 的金鑰管理 API 支援零停機輪換。

## 輪換策略

最安全的輪換模式是**先建立後刪除**：

1. 建立一個與舊金鑰具有相同權限的新金鑰
2. 將新金鑰部署到您的應用程式
3. 驗證新金鑰是否正常運作
4. 刪除舊金鑰

這樣可以確保零停機——在確認新金鑰正常運作之前，流量繼續使用舊金鑰。

***

## 第一步：建立新金鑰

使用[金鑰管理 API](/zh-Hant/api-reference/keys/create-key) 建立替換金鑰：

<Tabs>
  <Tab title="cURL">
    ```bash theme={null}
    curl -X POST https://api.arouter.ai/v1/keys \
      -H "Authorization: Bearer lr_live_xxxx" \
      -H "Content-Type: application/json" \
      -d '{
        "name": "production-v2",
        "allowed_providers": ["openai", "anthropic", "google"],
        "spending_limit": 500.00
      }'
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    import requests

    response = requests.post(
        "https://api.arouter.ai/v1/keys",
        headers={"Authorization": "Bearer lr_live_xxxx"},
        json={
            "name": "production-v2",
            "allowed_providers": ["openai", "anthropic", "google"],
            "spending_limit": 500.00,
        },
    )
    new_key = response.json()["key"]
    print(f"New key created: {new_key[:8]}...")
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript theme={null}
    const response = await fetch("https://api.arouter.ai/v1/keys", {
      method: "POST",
      headers: {
        Authorization: "Bearer lr_live_xxxx",
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        name: "production-v2",
        allowed_providers: ["openai", "anthropic", "google"],
        spending_limit: 500.0,
      }),
    });

    const { key } = await response.json();
    console.log(`New key: ${key.substring(0, 8)}...`);
    ```
  </Tab>
</Tabs>

**請立即儲存回傳的金鑰值** — ARouter 僅在建立時回傳完整金鑰一次。

***

## 第二步：更新您的應用程式

在部署環境中更新 `AROUTER_API_KEY` 環境變數（或對應的 Secret）：

```bash theme={null}
# 使用 .env 檔案範例
AROUTER_API_KEY=lr_live_new_key_here

# 更新 Kubernetes secret 範例
kubectl create secret generic arouter-credentials \
  --from-literal=api-key=lr_live_new_key_here \
  --dry-run=client -o yaml | kubectl apply -f -
```

重新部署或重啟應用程式以使新金鑰生效。

***

## 第三步：驗證新金鑰

在刪除舊金鑰之前，確認新金鑰正常運作：

<Tabs>
  <Tab title="cURL">
    ```bash theme={null}
    curl https://api.arouter.ai/v1/models \
      -H "Authorization: Bearer lr_live_new_key_here"
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    from openai import OpenAI

    # 使用新金鑰測試
    client = OpenAI(
        base_url="https://api.arouter.ai/v1",
        api_key="lr_live_new_key_here",
    )

    response = client.chat.completions.create(
        model="openai/gpt-5.4",
        messages=[{"role": "user", "content": "ping"}],
        max_tokens=5,
    )
    print("New key verified:", response.choices[0].message.content)
    ```
  </Tab>
</Tabs>

檢查 [ARouter 控制台](https://arouter.ai/keys)，確認請求已出現在新金鑰下。

***

## 第四步：刪除舊金鑰

確認新金鑰正常運作後，使用舊金鑰 ID 將其刪除：

<Tabs>
  <Tab title="cURL">
    ```bash theme={null}
    curl -X DELETE https://api.arouter.ai/v1/keys/key_oldid \
      -H "Authorization: Bearer lr_live_new_key_here"
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    import requests

    requests.delete(
        "https://api.arouter.ai/v1/keys/key_oldid",
        headers={"Authorization": "Bearer lr_live_new_key_here"},
    )
    print("Old key deleted")
    ```
  </Tab>
</Tabs>

***

## 自動輪換

對於高安全性環境，可以使用 CI/CD 系統或金鑰管理器按排程自動輪換：

### GitHub Actions 範例

```yaml theme={null}
name: Rotate ARouter Key

on:
  schedule:
    - cron: '0 0 1 * *'  # 每月執行

jobs:
  rotate:
    runs-on: ubuntu-latest
    steps:
      - name: Create new key
        id: create
        run: |
          NEW_KEY=$(curl -s -X POST https://api.arouter.ai/v1/keys \
            -H "Authorization: Bearer ${{ secrets.AROUTER_API_KEY }}" \
            -H "Content-Type: application/json" \
            -d '{"name": "production-auto-rotated"}' \
            | jq -r .key)
          echo "new_key=$NEW_KEY" >> $GITHUB_OUTPUT

      - name: Update secret
        uses: gliech/create-github-secret-action@v1
        with:
          name: AROUTER_API_KEY
          value: ${{ steps.create.outputs.new_key }}
          token: ${{ secrets.GH_TOKEN }}
```

***

## 列出活躍金鑰

列出所有活躍金鑰以稽核當前使用情況：

```bash theme={null}
curl https://api.arouter.ai/v1/keys \
  -H "Authorization: Bearer lr_live_xxxx"
```

回應：

```json theme={null}
{
  "data": [
    {
      "id": "key_abc123",
      "name": "production-v2",
      "created_at": "2025-01-15T10:00:00Z",
      "last_used_at": "2025-04-01T08:30:00Z",
      "spending_limit": 500.00
    },
    {
      "id": "key_def456",
      "name": "staging",
      "created_at": "2025-03-01T09:00:00Z",
      "last_used_at": "2025-04-01T07:15:00Z",
      "spending_limit": 50.00
    }
  ]
}
```

***

## 最佳實踐

* **定期輪換** — 對大多數應用程式而言，每月輪換是一個良好的基準
* **疑似洩露後立即輪換** — 不要等到下次排程輪換
* **使用描述性名稱** — 在金鑰名稱中包含版本或日期（如 `production-2025-04`、`production-v3`）
* **設定消費限額** — 始終為生產金鑰配置 `spending_limit` 以控制風險敞口
* **不同環境使用獨立金鑰** — 生產環境與預發布環境絕不共用同一金鑰
* **定期稽核** — 每月檢查金鑰列表，刪除不再使用的金鑰
* **將金鑰儲存在金鑰管理器中** — 使用 AWS Secrets Manager、HashiCorp Vault 或同類工具，而非版本控制中的 `.env` 檔案

完整金鑰管理指南請參閱[金鑰管理](/zh-Hant/guides/key-management)，完整 API 參考請參閱[金鑰管理 API](/zh-Hant/api-reference/keys/create-key)。
