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

#### 工厂方法

| 方法          | 签名                                                                                    | 在以下情况下使用 |
| ----------- | ------------------------------------------------------------------------------------- | -------- |
| `Succeeded` | `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` 如果 `provider` 为 `null`. |
| `Unregister` | `static bool Unregister(IConvaiAuthTokenProvider provider)` | 取消注册 `provider` 仅当它仍然是活动注册项时。返回 `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` 调用时被调用一次。抛出 `ArgumentNullException` 如果 `包装` 为 `null`. |

`GetTokenAsync` 返回 `AuthTokenResult.Failed` 当委托返回 `null`、空任务或 `null`仅空白字符串时；否则返回 `AuthTokenResult.Succeeded` 以及修剪后的令牌。

### `ConvaiAuthMode`

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

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

| 值           | Integer | 描述                                |
| ----------- | ------- | --------------------------------- |
| `ApiKey`    | `0`     | 从 `ConvaiSettings`读取账户 API 密钥。默认。 |
| `AuthToken` | `1`     | 从已注册的提供器或已配置的端点解析短期身份验证令牌。        |

### `ConvaiAuthTokenHttpMethod`

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

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

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

### `ConvaiAuthTokenHeader`

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

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

#### 属性

| 属性     | 类型       | 描述             |
| ------ | -------- | -------------- |
| `Name` | `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`            | 必需。作为 `end_user_id`.            |
| `endUserName`       | `string`            | 必需。作为 `end_user_metadata.name`. |
| `cancellationToken` | `CancellationToken` | 取消挂起的连接尝试。默认为 `default`.        |

返回 `IConvaiOperation<RoomSession>`.

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

#### 错误

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

前四种错误会在任何网络工作开始之前抛出；最后两种会在连接尝试期间抛出。两者都会以相同方式返回给调用方。

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

`Convai.Runtime` — 项目保存的 `ConvaiSettings` 资源，可通过 **编辑 > 项目设置 > 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 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/scripting-reference.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.
