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

# 身份验证

> 如何使用 FIM One API 进行身份验证

## 概述

FIM One API 支持两种身份验证方法：

1. **API 密钥** — 用于服务间集成的简单、长期有效的令牌
2. **JWT 令牌** — 来自用户登录的短期令牌（用于 SSE 端点）

大多数集成应使用 **API 密钥**。

## API 密钥

API 密钥是与您的用户账户关联的长期凭证。它们适用于：

* 服务器到服务器的集成
* 计划脚本和自动化
* 外部应用程序访问 FIM One

### 创建 API 密钥

1. 登录到您的 FIM One 门户
2. 转到 **设置 → API 密钥**
3. 点击 **创建 API 密钥**
4. 输入名称（例如，"生产集成"）
5. （可选）设置作用域以限制访问权限
6. （可选）设置过期日期
7. 点击 **创建**
8. 立即复制密钥 — 它只会显示一次

完整密钥看起来像：`fim_your44characterkeystringhere`（以 `fim_` 前缀开头）

### 使用 API 密钥

在 `Authorization` 标头中将密钥作为 Bearer 令牌包含：

```bash theme={null}
curl -H "Authorization: Bearer fim_your_api_key_here" \
  https://your-domain.com/api/conversations
```

或在 Python 中：

```python theme={null}
import requests

headers = {
    "Authorization": "Bearer fim_your_api_key_here"
}

response = requests.get(
    "https://your-domain.com/api/conversations",
    headers=headers
)
print(response.json())
```

### API 密钥功能

**可见性**: 每个密钥显示：

* 密钥前缀（前 8 个字符用于识别）
* 创建日期
* 最后使用时间戳
* 总请求数
* 活跃状态
* 过期日期（如果设置）

**管理**: 您可以：

* 启用/禁用密钥而无需删除它们
* 设置自动过期日期
* 永久删除密钥
* 跟踪使用模式

### 作用域

作用域限制 API 密钥可以访问的内容。如果未设置作用域，密钥具有完全访问权限。

可用作用域：

| 作用域          | 允许                                                                  |
| ------------ | ------------------------------------------------------------------- |
| `chat`       | POST /api/react, POST /api/dag, POST /api/chat/inject               |
| `agents`     | GET /api/agents, GET /api/agents/`{id}`                             |
| `kb`         | GET /api/knowledge-bases, POST /api/knowledge-bases/`{id}`/retrieve |
| `connectors` | 连接器 CRUD（connector\_specific 端点）                                    |
| `admin`      | 管理端点                                                                |

创建具有作用域的密钥：

```bash theme={null}
curl -X POST https://your-domain.com/api/me/api-keys \
  -H "Authorization: Bearer your_current_api_key_or_jwt" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Chat-only Integration",
    "scopes": "chat"
  }'
```

## JWT 令牌

JWT 令牌是短期的，在登录时颁发。它们用于：

* **SSE 流式端点**：在 `/api/react` 和 `/api/dag` 的请求体中传递令牌
* **门户会话**：前端身份验证

### 获取 JWT Token

当您通过网络门户登录或调用身份验证端点时，JWT token 会自动颁发：

```bash theme={null}
curl -X POST https://your-domain.com/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{
    "email": "user@example.com",
    "password": "your_password"
  }'
```

响应：

```json theme={null}
{
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "token_type": "bearer",
  "expires_in": 7200,
  "user": { ... }
}
```

### 使用 JWT 进行流式传输

对于 SSE 端点，在请求体中包含令牌：

```bash theme={null}
curl -X POST https://your-domain.com/api/react \
  -H "Content-Type: application/json" \
  -d '{
    "q": "What are the top 3 Python frameworks?",
    "token": "your_jwt_token_here"
  }'
```

或从 JavaScript 使用 `fetch` 和可读流（该端点仅支持 POST，因此仅支持 GET 的原生 `EventSource` 无法使用）：

```javascript theme={null}
const response = await fetch("https://your-domain.com/api/react", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    q: "Hello",
    token: "fim_your_api_key_here"
  })
});

const reader = response.body.getReader();
const decoder = new TextDecoder();

while (true) {
  const { done, value } = await reader.read();
  if (done) break;
  const chunk = decoder.decode(value);
  // Parse SSE events from chunk
  console.log(chunk);
}
```

### 令牌刷新

访问令牌在 2 小时后过期。使用刷新令牌获取新的访问令牌，无需重新登录：

```bash theme={null}
curl -X POST https://your-domain.com/api/auth/refresh \
  -H "Content-Type: application/json" \
  -d '{
    "refresh_token": "your_refresh_token_here"
  }'
```

## 安全最佳实践

### API 密钥

<Warning>
  **永远不要将 API 密钥提交到版本控制。** 它们提供对您数据的完全访问权限。
</Warning>

1. **存储在环境变量中**:
   ```bash theme={null}
   export FIM_API_KEY="fim_your_api_key_here"
   ```
   然后在代码中引用:
   ```python theme={null}
   api_key = os.environ.get("FIM_API_KEY")
   ```

2. **使用密钥轮换**:
   * 创建新密钥
   * 更新您的应用程序
   * 删除旧密钥
   * 每季度重复一次

3. **设置过期日期**:
   * 为临时集成使用短期密钥
   * 定期要求重新身份验证

4. **使用作用域密钥**:
   * 除非必要，否则不要使用"完全访问"密钥
   * 为不同的服务创建单独的密钥
   * 限制密钥泄露时的损害

5. **监控使用情况**:
   * 检查"最后使用"时间戳
   * 查看请求计数
   * 删除未使用的密钥

### JWT 令牌

1. **保持短生命周期**：访问令牌在 2 小时后过期
2. **安全存储**：
   * 在浏览器中：使用 HttpOnly cookies（比 localStorage 更安全）
   * 在服务器中：使用安全的会话存储
3. **不要在日志中暴露**：仅记录令牌前缀，不记录完整令牌
4. **仅使用 HTTPS**：不要通过未加密的连接发送令牌

## 速率限制

计划在未来版本中实现按密钥的速率限制。目前没有强制执行的按密钥请求限制。

## 故障排除

### 无效令牌错误

```json theme={null}
{
  "error": "invalid_token",
  "message": "The provided token is invalid or expired"
}
```

**原因**:

* API 密钥前缀错误（必须以 `fim_` 开头）
* JWT 令牌已过期（刷新它）
* 令牌格式错误或已损坏
* API 密钥已被删除

**解决方案**: 验证令牌格式并在必要时重新生成

### 未授权错误

```json theme={null}
{
  "error": "unauthorized",
  "message": "Authentication required"
}
```

**原因**:

* 未提供授权标头
* 请求体中缺少令牌（对于 SSE 端点）
* API 密钥已禁用

**解决方案**: 在每个请求中包含有效的令牌

### 禁止错误

```json theme={null}
{
  "error": "forbidden",
  "message": "Your API key does not have permission to access this resource"
}
```

**原因**:

* API 密钥具有作用域访问权限，缺少所需的作用域
* 用户账户具有受限权限

**解决方案**: 使用具有适当作用域的密钥或提高密钥权限

### 过期的令牌

```json theme={null}
{
  "error": "token_expired",
  "message": "Your token has expired. Please refresh your authentication."
}
```

**解决方案**：使用刷新令牌获取新的访问令牌：

```bash theme={null}
curl -X POST https://your-domain.com/api/auth/refresh \
  -d '{"refresh_token": "your_refresh_token"}'
```

## 环境变量设置

### Python

```python theme={null}
import os
from dotenv import load_dotenv
import requests

# Load from .env file
load_dotenv()

api_key = os.getenv("FIM_API_KEY")
base_url = os.getenv("FIM_API_BASE_URL", "https://your-domain.com/api")

headers = {"Authorization": f"Bearer {api_key}"}

# Now use in requests
response = requests.get(f"{base_url}/agents", headers=headers)
```

### Node.js

```javascript theme={null}
const api_key = process.env.FIM_API_KEY;
const base_url = process.env.FIM_API_BASE_URL || "https://your-domain.com/api";

const headers = {
  "Authorization": `Bearer ${api_key}`,
  "Content-Type": "application/json"
};

// Use in fetch
const response = await fetch(`${base_url}/agents`, {
  headers: headers
});
```

### Bash

```bash theme={null}
#!/bin/bash

FIM_API_KEY="${FIM_API_KEY:-$(cat ~/.fim_api_key)}"
FIM_API_BASE_URL="${FIM_API_BASE_URL:-https://your-domain.com/api}"

curl -H "Authorization: Bearer $FIM_API_KEY" \
  "$FIM_API_BASE_URL/agents"
```

## 支持

如有身份验证问题：

* 查看 [API 概览](/api/overview) 了解响应格式详情
* 使用 `GET /api/auth/verify` 检查令牌过期情况
* 如果您认为密钥已被泄露，请联系支持
