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

# 编写自定义令牌提供程序

注册一个自定义凭证提供程序，让你的后端为每次连接自动签发短期 Convai 身份验证令牌。

实现 `IConvaiAuthTokenProvider` 如果项目已经有能够生成 Convai 身份验证令牌的后端或登录层，并且你希望 SDK 在每次连接时自动调用它，请实现此接口。当项目使用 Auth Token 模式，并且你希望无需在每个调用位置修改连接代码即可解析令牌时，请参阅本页。

### 前提条件

* 项目的 `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`）的后端端点或 SDK。

### 实现此接口

`IConvaiAuthTokenProvider` 只有一个方法：

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

SDK 会在每次尝试建立新的房间连接时调用一次 `GetTokenAsync` 。成功时返回 `AuthTokenResult.Succeeded(token, expiresAtUtc)` ；令牌无法解析时返回 `AuthTokenResult.Failed(errorMessage)` 。 `expiresAtUtc` 为可选参数。

{% code title="Assets/Scripts/MyAuthTokenProvider.cs" %}

```csharp
using System;
using System.Threading;
using System.Threading.Tasks;
using Convai.Runtime.Core.Configuration;

public sealed class MyAuthTokenProvider : IConvaiAuthTokenProvider
{
    public async Task<AuthTokenResult> GetTokenAsync(CancellationToken cancellationToken)
    {
        try
        {
            string token = await MyBackend.RequestConvaiTokenAsync(cancellationToken);
            return string.IsNullOrWhiteSpace(token)
                ? AuthTokenResult.Failed("My backend returned an empty token.")
                : AuthTokenResult.Succeeded(token);
        }
        catch (Exception exception)
        {
            return AuthTokenResult.Failed($"My backend request failed ({exception.GetType().Name}).");
        }
    }
}
```

{% endcode %}

{% hint style="warning" %}
`IConvaiAuthTokenProvider` 实现不得记录或持久化返回的令牌。应将其视为仅适用于单次连接尝试的短期机密。
{% endhint %}

### 连接前注册提供程序

使用 `ConvaiAuthTokenProviderRegistry` 注册提供程序，并确保在首次连接尝试之前完成注册，通常可在较早调用的 `Awake`:

```csharp
using Convai.Runtime.Core.Configuration;
using UnityEngine;

public sealed class AuthBootstrap : MonoBehaviour
{
    private MyAuthTokenProvider _provider;

    private void Awake()
    {
        _provider = new MyAuthTokenProvider();
        ConvaiAuthTokenProviderRegistry.Register(_provider);
    }

    private void OnDestroy()
    {
        ConvaiAuthTokenProviderRegistry.Unregister(_provider);
    }
}
```

`ConvaiAuthTokenProviderRegistry.Register` 会替换当前已注册的提供程序。 `Unregister(provider)` 仅当它仍是当前活动注册项时才会将其移除； `Unregister()` 不带参数时，以及 `Clear()` 都会移除当前活动的提供程序。

{% hint style="warning" %}
`ConvaiAuthTokenProviderRegistry` 是一个进程内静态注册表，会在以下时机自动重置： `RuntimeInitializeLoadType.SubsystemRegistration`。每次域重新加载以及每次进入播放模式时都会触发此操作，因此，注册一次的提供程序无法在此之后继续使用——每次启动脚本运行时都要重新注册提供程序，不要认为调用一次就够了。
{% endhint %}

### 简单场景可使用委托

如果提供程序只需要进行一次异步查找，可以将 lambda 封装在 `DelegateAuthTokenProvider` 中，而不必编写完整的类：

```csharp
using Convai.Runtime.Core.Configuration;

ConvaiAuthTokenProviderRegistry.Register(
    new DelegateAuthTokenProvider(async cancellationToken =>
        await MyBackend.RequestConvaiTokenAsync(cancellationToken)));
```

`DelegateAuthTokenProvider` 封装了一个 `Func<CancellationToken, Task<string>>`。如果委托返回 `AuthTokenResult.Failed` ，则会在委托返回 `null`、空任务或空字符串时失败，因此委托只需返回令牌字符串或抛出异常。

### 验证设置

进入播放模式并连接角色。如果提供程序解析成功，连接将继续进行，且不会出现与身份验证相关的错误。如果失败，连接会通过常规连接错误处理流程显示来自 `AuthTokenResult.Failed` 的消息。

### 后续步骤

{% content-ref url="/pages/1e83cf2de6c0f33600727e9d53472326fe916861" %}
[使用现有身份验证令牌连接](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/authentication/connect-with-auth-token.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/custom-token-provider.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.
