> 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/auth-tokens.md).

# 使用认证令牌连接

通过在服务器端签发 auth token，并在浏览器中使用该 token 连接 Web SDK，从而将 Convai API 密钥保留在你的服务器上。

使用由您的服务器签发的身份验证令牌连接 Convai Web SDK，这样您的 API 密钥就不会传到浏览器。在发布任何与角色交互的页面之前，请先阅读本页。

### 为何使用身份验证令牌

API 密钥是您整个 Convai 账户的凭证。客户端程序包中的任何值都可能被打开页面的任何人读取，因此，随应用发布的 API 密钥可能会被复制并在您的应用之外使用。身份验证令牌由您的服务器使用 API 密钥创建，只有令牌会发送到浏览器。

```mermaid
sequenceDiagram
    participant Browser
    participant Server as Your server
    participant Convai
    Browser->>Server: Request a token
    Server->>Convai: POST /user/connect with CONVAI-API-KEY
    Convai-->>Server: apiAuthToken
    Server-->>Browser: Token
    Browser->>Convai: connect() with authToken
```

该图展示了 API 密钥始终保留在您的服务器上：浏览器只会持有令牌。

### 在您的服务器上签发令牌

发送一个 `POST` 请求到 `https://api.convai.com/user/connect` 并在 `CONVAI-API-KEY` 标头中提供您的 API 密钥。令牌位于 JSON 响应的 `apiAuthToken` 字段中。

{% tabs %}
{% tab title="Node.js" %}
{% code title="server/token.ts" %}

```typescript
export async function createConvaiToken(): Promise<string> {
  const response = await fetch('https://api.convai.com/user/connect', {
    method: 'POST',
    headers: {
      'CONVAI-API-KEY': process.env.CONVAI_API_KEY!,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({}),
  });
  if (!response.ok) {
    throw new Error(`Token request failed: ${response.status}`);
  }
  const data = await response.json();
  return data.apiAuthToken;
}
```

{% endcode %}
{% endtab %}

{% tab title="Python" %}

```python
import os
import requests

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

{% endtab %}
{% endtabs %}

通过您自己的端点公开此函数，并确保只有已登录的最终用户才能调用该端点。

### 使用令牌连接

传入 `authToken` 而不是 `apiKey`。其他选项均保持不变。

{% tabs %}
{% tab title="React" %}

```tsx
import { useConvaiClient } from '@convai/web-sdk/react';
import { ConvaiWidget } from '@convai/web-widget/react';

export function Assistant({ token }: { token: string }) {
  const client = useConvaiClient({
    authToken: token,
    characterId: 'YOUR_CHARACTER_ID',
  });

  return <ConvaiWidget convaiClient={client} />;
}
```

{% endtab %}

{% tab title="TypeScript" %}

```typescript
import { ConvaiClient } from '@convai/web-sdk/core';

const token = await fetch('/api/convai-token').then((r) => r.text());

const client = new ConvaiClient({
  authToken: token,
  characterId: 'YOUR_CHARACTER_ID',
});

await client.connect();
```

{% endtab %}
{% endtabs %}

原版 `createConvaiWidget()` 辅助函数也接受 `authToken` 来替代 `apiKey` 如果你让它创建客户端。

connect() 中的凭据规则 `connect()`:

| 配置                        | 结果                                                                                        |
| ------------------------- | ----------------------------------------------------------------------------------------- |
| `authToken` 已设置           | SDK 会在 `API-AUTH-TOKEN` 标头中发送该令牌。如果同时设置了 `apiKey` ，则优先使用该令牌。                              |
| 仅 `apiKey` 已设置            | SDK 会在 `X-API-Key` 标头中发送该密钥。                                                              |
| 两者均未设置，或未提供 `characterId` | `connect()` 会抛出错误： `Either apiKey or authToken is required, and characterId is required`. |

为会话创建的长期记忆管理器使用相同的凭据，因此使用令牌也可以调用记忆功能。请参阅 [使用长期记忆](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/long-term-memory.md).

{% hint style="danger" %}
不要在面向公众的网页浏览器代码中放置 API 密钥。请将 `apiKey` 用于本地开发和服务器端工具。
{% endhint %}

### 验证连接

从网页发起连接，并确认 `connect()` 成功返回，且触发 `botReady` 事件。在浏览器的网络面板中， `/connect` 请求应包含 `API-AUTH-TOKEN` 标头，且不包含 `X-API-Key` 标头。

### 后续步骤

{% content-ref url="/pages/1ef8009eea712d4c41fd7a2a07e473a277395698" %}
[处理错误和断开连接](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/error-handling.md)
{% endcontent-ref %}

{% content-ref url="/pages/4f33318cc644cad5dc970e09e48c72b8b29329f6" %}
[使用长期记忆](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/long-term-memory.md)
{% endcontent-ref %}

{% content-ref url="/pages/dff296725774f9173a7391e28344f5f94cf35b60" %}
[配置和类型参考](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/vanilla-typescript/best-practices-and-type-definitions.md)
{% endcontent-ref %}


---

# 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 by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/auth-tokens.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
