# 認證

使用 API keys 認證請求，遵循安全實務，並處理認證錯誤。

Felo API Platform 的所有 API 請求都需要使用 API Key 認證。本指南說明如何認證請求，以及如何處理常見認證問題。

## API Key 認證

Felo 的 v2 endpoints 使用 API Key 認證。你的 API Key 用於識別應用，並授予訪問平臺能力的許可權。

### 工作方式

1. 從 [Felo API Platform API Keys 頁面](https://openapi.felo.ai/console/api-keys) 取得 API Key
2. 在每個 API request 的 `Authorization` header 中加入 API Key
3. 平臺驗證 API Key 並處理請求

### Header 格式

使用 Bearer 認證方案，把 API Key 放入 `Authorization` header：

```
Authorization: Bearer YOUR_API_KEY
```

### 示例請求

```bash
curl -X POST https://openapi.felo.ai/v2/chat   -H "Authorization: Bearer sk_live_abc123xyz789"   -H "Content-Type: application/json"   -d '{"query": "What is machine learning?"}'
```

## 取得 API Key

1. 開啟 [Felo API Platform API Keys 頁面](https://openapi.felo.ai/console/api-keys)
2. 如果系統提示，請登入 Felo 賬戶
3. 輸入 key 名稱並點選 **建立 Key**
4. key 出現後複製完整內容。完整 key 只顯示一次
5. 安全儲存 key，並把它作為 `FELO_API_KEY` 使用

::: warning 保護你的 API Key
API Key 可以訪問你的 Felo 賬戶能力，必須保密。不要公開分享、提交到版本控制，或暴露在使用者端程式碼中。
:::

## 安全最佳實踐

### 1. 安全儲存 API Keys

不要把 API Key 硬編碼在原始碼裡：

```python
# Bad - API Key exposed in code
api_key = "sk_live_abc123xyz789"
```

請使用環境變數或安全設定：

```python
# Good - API Key from environment
import os
api_key = os.environ.get('FELO_API_KEY')
```

### 2. 使用環境變數

**Linux/macOS:**
```bash
export FELO_API_KEY="sk_live_abc123xyz789"
```

**Windows PowerShell:**
```powershell
$env:FELO_API_KEY="sk_live_abc123xyz789"
```

### 3. 定期輪換 Keys

定期生成新 API Keys，並撤銷舊 key，以降低安全風險。

### 4. 為不同環境使用不同 Keys

為 development、staging 和 production 建立不同 API Keys。

### 5. 不要在使用者端暴露 Keys

API Keys 只應在 server-side code 中使用。不要放入 frontend JavaScript、mobile app source code、public repositories 或 client-side config。

## 認證錯誤

完整的錯誤結構、限流 headers 與重試策略，請參閱[錯誤、限流與重試](https://openapi.felo.ai/zh-TW/docs/guides/errors-and-limits.md)。

### 常見錯誤碼

| HTTP | Code | 說明 |
|------|------|------|
| 401 | `UNAUTHORIZED` | Key 缺少、無效、過期或已撤銷 |
| 429 | `RATE_LIMITED` | 請求過多；請參閱[錯誤、限流與重試](https://openapi.felo.ai/zh-TW/docs/guides/errors-and-limits.md)指南 |

被拒絕的請求會在 `message` 中回傳 key 狀態：

```json
{
  "status": 401,
  "code": "UNAUTHORIZED",
  "message": "API Key is required",
  "request_id": "..."
}
```

`status` 就是 HTTP 狀態碼。已撤銷的 key 會回報 `API Key has been revoked (keyPrefix=...)`。請依據 HTTP 狀態碼與 `code` 分支處理，不要比對 `message` 的具體文字。

## 疑難排解

若認證失敗：

1. 確認 header 完全是 `Authorization: Bearer YOUR_API_KEY`。
2. 在 [API Keys 頁面](https://openapi.felo.ai/console/api-keys) 確認 key 未被撤銷。
3. 確認目前環境使用的是你預期的 key。
4. 若舊 key 已刪除或輪替，請生成新 key。完整 key 只在建立時顯示一次。

涵蓋認證與整個平臺的症狀排查清單，請參閱[故障排查](https://openapi.felo.ai/zh-TW/docs/faq/troubleshooting.md)。

### 範例：偵錯認證

```python
import requests

url = "https://openapi.felo.ai/v2/chat"
api_key = "YOUR_API_KEY"

# Correct format
headers = {
    "Authorization": f"Bearer {api_key}",
    "Content-Type": "application/json"
}

response = requests.post(url, headers=headers, json={"query": "test"})

if response.status_code == 401:
    error = response.json()
    print(f"Authentication failed: {error['code']}")
    print(f"Message: {error['message']}")
    print(f"Request ID: {error['request_id']}")
else:
    print("Authentication successful!")
```

## Rate Limiting

限流**按 endpoint** 執行，而不是按 API Key 全域性執行。目前只有 [`/v2/chat`](https://openapi.felo.ai/zh-TW/docs/api-reference/chat.md#速率限制) 會實際執行限流；有效付費 Felo 訂閱的使用者可豁免。其他 `/v2/**` endpoints 沒有強制限流。

429 回應會包含 `X-RateLimit-*` headers 與 `Retry-After`。請一律從 response headers 讀取實際生效的限制，而不是文件。

完整的限流維度、headers 與重試策略，請參閱[錯誤、限流與重試](https://openapi.felo.ai/zh-TW/docs/guides/errors-and-limits.md)。

## 需要幫助？

1. 仔細檢查本指南
2. 檢視 [Getting Started](https://openapi.felo.ai/zh-TW/docs/getting-started.md)
3. 在 [API Keys 頁面](https://openapi.felo.ai/console/api-keys) 驗證 API Key
4. 帶上 request ID 聯絡 support@felo.ai

## 下一步

- [Getting Started Guide](https://openapi.felo.ai/zh-TW/docs/getting-started.md) - 學會發出第一個 API 呼叫
- [Chat API Reference](https://openapi.felo.ai/zh-TW/docs/api-reference/chat.md) - 探索 Chat API 文件
