> 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/scripting-reference.md).

# 身份验证脚本参考

Convai Unity SDK 身份验证 API 的参考，包括令牌提供程序接口、注册表和设置访问器。

Convai Unity SDK 中公共身份验证接口的完整 API 参考。类型位于 `Convai.Runtime.Core.Configuration` 命名空间中，除非另有说明。

### `IConvaiAuthTokenProvider`

`Convai.Runtime.Core.Configuration` — 接口

为 Convai 运行时连接解析短期凭据。在任意类上实现此接口，即可从您自己的后端提供令牌。

```csharp
public interface IConvaiAuthTokenProvider
{
    Task<AuthTokenResult> GetTokenAsync(CancellationToken cancellationToken);
}
```

#### 方法

| 方法              | 签名                                                                         | 说明                                             |
| --------------- | -------------------------------------------------------------------------- | ---------------------------------------------- |
| `GetTokenAsync` | `Task<AuthTokenResult> GetTokenAsync(CancellationToken cancellationToken)` | 解析一个新的身份验证令牌。每次新的房间连接尝试都会调用一次；SDK 不会在连接之间缓存结果。 |

{% hint style="warning" %}
实现不得记录或持久化返回的令牌。
{% endhint %}

### `AuthTokenResult`

`Convai.Runtime.Core.Configuration` — 只读结构体

由以下方法返回的结果： `IConvaiAuthTokenProvider.GetTokenAsync`.

#### 属性

| 属性             | 类型                | 说明                                      |
| -------------- | ----------------- | --------------------------------------- |
| `IsSuccess`    | `bool`            | `true` 当 `Token` 已成功解析。                 |
| `Token`        | `string`          | 解析出的身份验证令牌。为空时表示 `IsSuccess` 是 `false`. |
| `ExpiresAtUtc` | `DateTimeOffset?` | 令牌的可选过期时间，已标准化为 UTC。 `null` 如果未提供则为空。   |
| `错误消息`         | `string`          | 失败原因。为空时表示 `IsSuccess` 是 `true`.        |

#### 工厂方法

| 方法       | 签名                                                                                    | 在以下情况使用： |
| -------- | ------------------------------------------------------------------------------------- | -------- |
| `成功`     | `static AuthTokenResult Succeeded(string token, DateTimeOffset? expiresAtUtc = null)` | 令牌已解析。   |
| `Failed` | `static AuthTokenResult Failed(string errorMessage)`                                  | 令牌解析失败。  |

### `ConvaiAuthTokenProviderRegistry`

`Convai.Runtime.Core.Configuration` — 静态类

进程本地的注册点，用于开发者提供的 `IConvaiAuthTokenProvider`。请在第一次连接尝试之前注册提供程序。

#### 属性

| 属性             | 类型     | 说明                     |
| -------------- | ------ | ---------------------- |
| `IsRegistered` | `bool` | `true` 当当前已注册自定义提供程序时。 |

#### 方法

| 方法           | 签名                                                          | 说明                                                                  |
| ------------ | ----------------------------------------------------------- | ------------------------------------------------------------------- |
| `Register`   | `static void Register(IConvaiAuthTokenProvider provider)`   | 注册或替换当前活动提供程序。若发生以下情况则抛出 `ArgumentNullException` 如果 `提供方` 是 `null`. |
| `Unregister` | `static bool Unregister(IConvaiAuthTokenProvider provider)` | 取消注册 `提供方` 仅当它仍是活动注册时。返回 `true` 在移除时为 true。                         |
| `Unregister` | `static void Unregister()`                                  | 取消注册当前处于活动状态的提供程序。                                                  |
| `清除`         | `static void Clear()`                                       | 清除当前注册。                                                             |

{% hint style="warning" %}
注册表会在以下时自动重置： `RuntimeInitializeLoadType.SubsystemRegistration`，它会在每次域重新加载以及每次进入 Play 模式时运行。请在每次此类重新加载后重新注册提供程序，而不要依赖一次性的启动调用。
{% endhint %}

### `DelegateAuthTokenProvider`

`Convai.Runtime.Core.Configuration` — 实现以下接口的密封类： `IConvaiAuthTokenProvider`

将开发者提供的异步委托适配为提供程序，适用于不需要专用类的情况。

#### 构造函数

| 构造函数                        | 签名                                                                               | 说明                                                                                                               |
| --------------------------- | -------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
| `DelegateAuthTokenProvider` | `DelegateAuthTokenProvider(Func<CancellationToken, Task<string>> getTokenAsync)` | 包装 `getTokenAsync`，它会在每次 `GetTokenAsync` 调用时调用一次。若发生以下情况则抛出 `ArgumentNullException` 如果 `getTokenAsync` 是 `null`. |

`GetTokenAsync` 返回 `AuthTokenResult.Failed` 当委托返回 `null`、空任务，或 `null`/仅包含空白字符的字符串时；否则返回 `AuthTokenResult.Succeeded` 并使用修剪后的令牌。

### `ConvaiAuthMode`

`Convai.Runtime.Core.Configuration` — 枚举

用于运行时 Convai 房间连接的身份验证策略。

| 值           | 整数  | 说明                                     |
| ----------- | --- | -------------------------------------- |
| `ApiKey`    | `0` | 从以下位置读取账户 API 密钥： `ConvaiSettings`。默认。 |
| `AuthToken` | `1` | 从已注册提供程序或已配置端点解析短期身份验证令牌。              |

### `ConvaiAuthTokenHttpMethod`

`Convai.Runtime.Core.Configuration` — 枚举

配置的 Auth Token 模式端点所使用的 HTTP 方法（在 **Project Settings > Convai SDK > Credentials**).

| 值      | 整数  | 说明                                 |
| ------ | --- | ---------------------------------- |
| `Get`  | `0` | 发送一个 HTTP `GET` 请求，不带请求体。默认。       |
| `Post` | `1` | 发送一个 HTTP `POST` 请求，带空 JSON 对象请求体。 |

### `ConvaiAuthTokenHeader`

`Convai.Runtime.Core.Configuration` — 可序列化结构体

发送到 Auth Token 模式端点的单个静态 HTTP 标头名称/值对。

#### 属性

| 属性   | 类型       | 说明              |
| ---- | -------- | --------------- |
| `名称` | `string` | 标头名称。绝不 `null`. |
| `值`  | `string` | 标头值。绝不 `null`.  |

#### 构造函数

| 构造函数                    | 签名                                                 | 说明                           |
| ----------------------- | -------------------------------------------------- | ---------------------------- |
| `ConvaiAuthTokenHeader` | `ConvaiAuthTokenHeader(string name, string value)` | 创建一个标头对。 `null` 参数会规范化为空字符串。 |

### `ConvaiManager.ConnectWithAuthTokenAsync`

`Convai.Runtime.Components`

使用显式提供的身份验证令牌进行连接，而不是使用已注册提供程序或端点。请参见 [使用现有身份验证令牌进行连接](/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/authentication/connect-with-auth-token.md) 了解用法。

```csharp
public IConvaiOperation<RoomSession> ConnectWithAuthTokenAsync(
    string authToken,
    string endUserId,
    string endUserName,
    CancellationToken cancellationToken = default)
```

| 参数                  | 类型                  | 说明                                          |
| ------------------- | ------------------- | ------------------------------------------- |
| `authToken`         | `string`            | 必填。仅用于此次连接的 Convai 身份验证令牌。                  |
| `endUserId`         | `string`            | 必填。发送给 Convai 时作为 `end_user_id`.            |
| `endUserName`       | `string`            | 必填。发送给 Convai 时作为 `end_user_metadata.name`. |
| `cancellationToken` | `CancellationToken` | 取消待处理的连接尝试。默认为 `默认`.                        |

返回 `IConvaiOperation<RoomSession>`.

以下每个失败都带有一个 `ConvaiOperationException`，而您如何接收它取决于您如何调用该方法。等待该操作会重新抛出异常，因此 `try`/`catch` 周围的 `await` 可处理所有情况。如果您不想捕获异常，请保留该操作而不要等待它，并读取 `IsSuccessful`, `HasError`，以及 `Error` 为 true 后再读取— `IsCompleted` ， `Error` 包含相同的代码和消息。

#### 错误

| 错误代码                          | Message                                       | 原因                                  |
| ----------------------------- | --------------------------------------------- | ----------------------------------- |
| `ConnectionInvalidToken`      | `需要一个非空的 Convai 身份验证令牌。`                      | `authToken` 为空或仅包含空白字符。             |
| `ConnectionBadRequest`        | `需要一个非空的最终用户 ID。`                             | `endUserId` 为空或仅包含空白字符。             |
| `ConnectionBadRequest`        | `需要一个非空的最终用户名称。`                              | `endUserName` 为空或仅包含空白字符。           |
| `ConnectionFailed`            | `ConvaiRoomManager 不可用。`                      | 管理器对象上没有房间管理器。                      |
| `ConfigAuthTokenModeRequired` | `显式身份验证令牌连接需要在 Convai 项目设置中启用 Auth Token 模式。` | 项目的身份验证模式是 `ConvaiAuthMode.ApiKey`. |
| `ConnectionInvalidToken`      | `连接令牌无效`                                      | Convai 拒绝了所提供的令牌。                   |

前四个会在任何网络工作开始之前抛出；后两个则在连接尝试期间抛出。二者都会以相同方式传递给调用方。

### `ConvaiSettings` 身份验证访问器

`Convai.Runtime` — 项目已保存的 `ConvaiSettings` 资源，可通过 **Edit > Project Settings > Convai SDK**.

#### 属性

| 属性                       | 类型                          | 说明                                                                                                                             |
| ------------------------ | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
| `AuthMode`               | `ConvaiAuthMode`            | 项目配置的身份验证模式。                                                                                                                   |
| `AuthTokenEndpointUrl`   | `string`                    | 已配置的 Auth Token 模式端点 URL，已修剪。若未配置则为空。                                                                                          |
| `AuthTokenHttpMethod`    | `ConvaiAuthTokenHttpMethod` | 用于调用已配置端点的 HTTP 方法。                                                                                                            |
| `AuthTokenResponseField` | `string`                    | 在端点响应中包含已解析令牌的 JSON 字段或点分隔字段路径。默认值为 `apiAuthToken` ，未设置时。                                                                      |
| `AuthTokenHeaders`       | `ConvaiAuthTokenHeader[]`   | 发送到已配置端点的静态标头。若未配置则为空数组。                                                                                                       |
| `HasValidAuthConfig`     | `bool`                      | `true` 当所选模式拥有足够配置以尝试连接时：对于 `ApiKey`，已存在 API 密钥；对于 `AuthToken`，要么已通过 `ConvaiAuthTokenProviderRegistry` 注册了提供程序，要么已配置有效的端点 URL。 |

端点 URL 验证——要求使用 HTTPS，除本地开发期间的 HTTP 回环地址外——会在 SDK 从已配置端点解析令牌时在内部执行。没有公开方法可在您自己的代码中运行该检查；请改为读取 `HasValidAuthConfig` ，以确认项目具备足够的配置进行连接。

### 下一步

{% 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/1e83cf2de6c0f33600727e9d53472326fe916861" %}
[使用现有身份验证令牌连接](/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/authentication/connect-with-auth-token.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/scripting-reference.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.
