> 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/convai-unity-sdk/authentication/connect-with-auth-token.md). Agents can also search and read this documentation through its [MCP server](https://docs.convai.com/api-docs/~gitbook/mcp).

# 使用现有身份验证令牌连接

当你的登录层已经持有一个已签发的 Convai 身份验证令牌时，直接将其传入单次连接调用。

调用 `ConnectWithAuthTokenAsync` 适用于以下情况：项目已在其他位置解析 Convai 身份验证令牌——例如，在玩家进入场景前通过登录流程请求令牌——并且你想将该令牌传递给单次连接尝试，而不是注册提供程序。

### 前提条件

* 项目的 `ConvaiSettings` 资源中已将 `AuthMode` 设为 `AuthToken`。请参阅 [配置 Auth Token 模式](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/authentication/configure-auth-token-mode.md).
* 从你自己的后端获取的有效、未过期的 Convai 身份验证令牌（即 `apiAuthToken`）。
* 用于连接玩家的稳定、非机密终端用户 ID 和显示名称。

{% hint style="info" %}
如果场景组件或由登录触发的流程可以自行解析令牌，请改为注册 [`IConvaiAuthTokenProvider`](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/authentication/custom-token-provider.md) 。当调用连接的代码中已存在令牌时，请使用 `ConnectWithAuthTokenAsync` ——例如，在登录调用返回令牌后立即使用。
{% endhint %}

### 调用 ConnectWithAuthTokenAsync

`ConvaiManager.ActiveManager.ConnectWithAuthTokenAsync` 接收令牌以及本次连接的终端用户身份信息：

```csharp
using System.Threading;
using System.Threading.Tasks;
using Convai.Runtime.Components;
using Convai.Runtime.Core.Async;
using UnityEngine;

public async Task ConnectSignedInPlayerAsync(
    string convaiAuthToken,
    string playerAccountId,
    string playerDisplayName,
    CancellationToken cancellationToken)
{
    try
    {
        var session = await ConvaiManager.ActiveManager.ConnectWithAuthTokenAsync(
            convaiAuthToken,
            playerAccountId,
            playerDisplayName,
            cancellationToken);
    }
    catch (ConvaiOperationException exception)
    {
        Debug.LogError($"Auth-token connection failed: {exception.Message}");
    }
}
```

这三个字符串参数均为必填项。如果 `authToken`, `endUserId`或 `endUserName` 为空或仅包含空白字符，则会抛出 `ConvaiOperationException` ，且不会发起任何网络调用。

| 参数                  | 映射到                      | 说明                         |
| ------------------- | ------------------------ | -------------------------- |
| `authToken`         | 仅用于本次连接的请求凭据             | 要使用的短期 Convai 身份验证令牌。      |
| `endUserId`         | `end_user_id`            | 用于连接玩家的稳定、非机密标识符。          |
| `endUserName`       | `end_user_metadata.name` | 玩家的显示名称。                   |
| `cancellationToken` | —                        | 取消待处理的连接尝试。默认值为 `default`. |

{% hint style="warning" %}
`ConnectWithAuthTokenAsync` 仅在这一次连接尝试中使用提供的令牌。SDK 不会缓存该令牌，因此后续直接调用 `ConnectAsync()` 不会重用它——使用此方式建立每次连接前，都要获取新的令牌。
{% endhint %}

### 项目为何仍必须处于 Auth Token 模式

向 `ConnectWithAuthTokenAsync` 传递令牌并不会切换项目的身份验证模式。如果 `AuthMode` 仍为 `ApiKey`，连接将失败，并返回错误代码 `ConfigAuthTokenModeRequired` 和以下消息：

```
显式令牌身份验证连接要求在 Convai 项目设置中启用 Auth Token 模式。
```

在使用此方法前，请将 `AuthMode` 设为 `AuthToken` ，并在 **Edit > Project Settings > Convai SDK > Credentials** 中进行设置；即使此处未配置端点 URL 或已注册的提供程序，也必须如此。

### 验证连接

使用有效令牌调用 `ConnectWithAuthTokenAsync` ，并确认返回的 `RoomSession` 能够正常解析且不抛出异常。如果令牌无效或已过期，该调用会抛出 `ConvaiOperationException` ，错误代码为 `ConnectionInvalidToken` ，消息为 `Connection token is invalid`.

### 后续步骤

{% content-ref url="/pages/6114741d5fa8999fa38b083a9727daac51fa40ab" %}
[编写自定义令牌提供程序](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/authentication/custom-token-provider.md)
{% endcontent-ref %}

{% content-ref url="/pages/fb645a3f7b0858dadf0b26ee09f168a43e9e98b7" %}
[身份验证脚本参考](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/authentication/scripting-reference.md)
{% endcontent-ref %}

{% content-ref url="/pages/2b331d8b6d61de917a4ae462f423b45b693555f4" %}
[身份验证故障排查](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/authentication/troubleshooting.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/convai-unity-sdk/authentication/connect-with-auth-token.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.
