> 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` | —                        | 取消挂起的连接尝试。默认为 `default`. |

{% hint style="warning" %}
`ConnectWithAuthTokenAsync` 仅将所提供的令牌用于那一次连接尝试。SDK 不会缓存它，因此后续的普通 `ConnectAsync()` 调用不会复用它——请在每次以这种方式发起连接之前解析一个新的令牌。
{% endhint %}

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

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

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

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

### 验证连接

调用 `ConnectWithAuthTokenAsync` 使用有效令牌，并确认返回的 `房间会话` 能够成功解析且不抛出异常。如果令牌无效或已过期，该调用会抛出一个 `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 dynamically by asking a question.

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

```
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=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
