> 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).

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

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

调用 `ConnectWithAuthTokenAsync` 当你的项目已经在其他地方解析出 Convai 身份验证令牌时——例如，在玩家进入场景之前请求令牌的登录流程中——并且你希望把该令牌交给一次单独的连接尝试，而不是注册一个提供程序。

### 前置条件

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

{% hint style="info" %}
如果场景组件或由登录触发的流程可以自行解析令牌，请改为注册一个 [`IConvaiAuthTokenProvider`](/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` | —                        | 取消待处理的连接尝试。默认为 `默认`.  |

{% hint style="warning" %}
`ConnectWithAuthTokenAsync` 仅将提供的令牌用于那一次连接尝试。SDK 不会缓存它，因此稍后普通的 `ConnectAsync()` 调用不会重用它——因此每次通过这种方式连接前都要获取一个新的令牌。
{% endhint %}

### 为什么项目仍必须处于身份验证令牌模式

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

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

设置 `AuthMode` 为 `AuthToken` 在 **编辑 > 项目设置 > Convai SDK > 凭据** 在使用此方法之前，即使那里没有配置端点 URL 或已注册提供程序。

### 验证连接

调用 `ConnectWithAuthTokenAsync` 使用有效令牌并确认返回的 `RoomSession` 能够成功解析且不抛出异常。如果令牌无效或已过期，该调用会抛出一个 `ConvaiOperationException` 并带有错误代码 `ConnectionInvalidToken` 和消息 `连接令牌无效`.

### 下一步

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

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

{% content-ref url="/pages/2b331d8b6d61de917a4ae462f423b45b693555f4" %}
[身份验证故障排查](/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.
