> For the complete documentation index, see [llms.txt](https://docs.convai.com/api-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/shen-fen-yan-zheng-ling-pai.md).

# 身份验证令牌

### 为什么认证令牌很重要

你的 API 密钥拥有对 Convai 账户的完全访问权限。把它打包进客户端意味着任何查看源代码的人都可以提取它并无限制地使用。认证令牌具有作用域、短期有效且可撤销——这是生产环境的正确选择。

***

### 流程

```
客户端                  你的服务器              Convai API
  |                         |                        |
  |  "开始对话"   |                        |
  |-----------------------> |                        |
  |                         |  POST /user/connect    |
  |                         |  CONVAI-API-KEY: ...   |
  |                         |----------------------->|
  |                         |  { apiAuthToken, ... } |
  |                         |<-----------------------|
  |  { authToken }          |                        |
  |<----------------------- |                        |
  |                         |                        |
  |  new ConvaiClient({ authToken })                 |
  |------------------------------------------------->|
```

API 密钥不会离开你的服务器。

***

### 1. 生成令牌（服务器端）

```
POST https://api.convai.com/user/connect
CONVAI-API-KEY: <your-api-key>
Content-Type: application/json
```

**响应**

```json
{
  "apiAuthToken": "your_auth_token_here",
  "expirationTime": "2026-06-11T13:00:00Z"
}
```

该令牌有效期为 **1 小时**。你可以在当前令牌仍然有效时生成一个新令牌。

**示例（Python）**

```python
import requests

def get_auth_token(api_key: str) -> str:
    response = requests.post(
        "https://api.convai.com/user/connect",
        headers={
            "CONVAI-API-KEY": api_key,
            "Content-Type": "application/json",
        },
        json={},
    )
    response.raise_for_status()
    return response.json()["apiAuthToken"]
```

***

### 2. 在 SDK 中使用令牌

传入 `authToken` 而不是 `apiKey`。其他一切保持不变。

```ts
const client = useConvaiClient({
  // apiKey: '...',    ← 绝不要把它发布到客户端代码中
  authToken: await fetchTokenFromYourServer(),
  characterId: '...',
  endUserId: 'user@example.com',
});
```

一旦会话开始，在该会话期间令牌将不再被检查——WebRTC/WebSocket 连接会独立持续存在。

***

### 3. 延长令牌

如果你在令牌过期前需要更多时间，可以从服务器延长它：

```
POST https://api.convai.com/user/extend-token
CONVAI-API-KEY: <your-api-key>
Content-Type: application/json

{
  "apiAuthToken": "your_auth_token_here"
}
```

***

### 4. 撤销令牌

立即撤销令牌——例如，当用户登出时：

```
POST https://api.convai.com/user/revoke-token
CONVAI-API-KEY: <your-api-key>
Content-Type: application/json

{
  "apiAuthToken": "your_auth_token_here"
}
```

撤销令牌不会结束已处于活动状态的会话。

***

### API 参考

#### `ConvaiConfig`

| 字段          | 类型       | 说明                                  |
| ----------- | -------- | ----------------------------------- |
| `apiKey`    | `string` | 你的 Convai API 密钥。仅限服务器端使用，或在开发期间使用。 |
| `authToken` | `string` | 短期有效的认证令牌。更适合生产环境中的客户端使用。           |

且仅有一个 `apiKey` 或 `authToken` 必须设置。

#### 令牌端点

| 端点                        | 说明              |
| ------------------------- | --------------- |
| `POST /user/connect`      | 生成新令牌（1 小时 TTL） |
| `POST /user/extend-token` | 延长现有令牌的过期时间     |
| `POST /user/revoke-token` | 立即使令牌失效         |

所有端点都需要 `CONVAI-API-KEY` 位于请求头中。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/shen-fen-yan-zheng-ling-pai.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
