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

# 自定义身份提供器

实现自定义最终用户身份提供程序，将 Convai 的记忆和 MAU 跟踪关联到你自己的身份验证系统、学习者记录或自助终端登录流程。

Convai 的长期记忆、MAU（月活跃用户）跟踪和最终用户管理功能，都依赖于为每位用户提供稳定且一致的标识符。对于大多数培训模拟和交互式体验，你会希望将默认的设备标识符替换为对应用有意义的标识符——例如身份验证系统中的用户 ID、学习者记录编号，或任何能在不同会话和设备间唯一标识同一用户的稳定字符串。

### 前提条件

* 一个可正常运行且带有 `ConvaiManager` 组件的 Convai 场景
* 要让每位用户的记忆可见，必须为角色启用 [长期记忆](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/features/long-term-memory.md) 功能
* 你自己的用户登录或身份系统，用于提供稳定的用户 ID

如果你还没有用户登录系统，默认的设备标识符就足够了——等身份验证系统就绪后再回来。

### 身份提供程序接口

两个接口用于控制 SDK 如何识别当前用户。

#### IEndUserIdentityProvider

主要接口。SDK 会在每次 `GetEndUserId()` 时调用一次 `ConnectAsync()` ，并将返回结果作为最终用户标识符发送给 Convai。

```csharp
public interface IEndUserIdentityProvider
{
    string GetEndUserId();
}
```

返回的字符串必须符合以下要求：

* 不得为 null 或空字符串。空字符串会导致连接失败。
* 必须稳定：同一用户在同一设备上（或跨设备）都必须在不同会话中返回相同的 ID。
* 每位用户的 ID 必须唯一。多个用户共用同一 ID 会导致他们的长期记忆混杂。

{% hint style="warning" %}
如果两个不同的用户解析为同一 ID，他们的长期记忆条目会在不发出任何提示的情况下合并。系统不会报错——但数据会出错。请确保 ID 来源在整个用户群体中全局唯一。
{% endhint %}

#### IEndUserMetadataProvider

可选。提供随连接请求一同发送给 Convai 的附加键值元数据。可用于传递显示名称、角色代码、部门 ID，或任何应与用户记录一同提供的上下文信息。

```csharp
public interface IEndUserMetadataProvider
{
    IReadOnlyDictionary<string, object> GetEndUserMetadata();
}
```

字典可以为空，但不能为 `null`。值必须是可序列化为 JSON 的基本类型（`string`, `int`, `float`, `bool`）。不可序列化的值会被静默丢弃。

### 默认行为

`DeviceEndUserIdProvider` 是 SDK 的默认提供程序。它的行为因上下文而异：

| 上下文                      | 来源                                                     | 稳定性                                    |
| ------------------------ | ------------------------------------------------------ | -------------------------------------- |
| 玩家构建版本（Android、iOS、PC 等） | `SystemInfo.deviceUniqueIdentifier` ，并在必要时回退到持久化的 GUID | 每台设备都稳定；重新安装操作系统或清除设备数据后会重置            |
| Unity Editor             | 存储在 `PlayerPrefs` 中，使用的键为 `convai.end_user_id`         | 每次 Editor 安装都保持稳定；若 `PlayerPrefs` 会被清除 |

在以下情况下替换默认值：

* 您的应用有自己的登录系统，并且会话必须跟随用户而非设备。
* 多个学习者共用一台设备（自助终端模式、共享实验室设备）。
* 您需要跨设备保持连续性（移动设备 + 桌面设备）。
* 合规要求用户 ID 与您自己的权威数据源中的 ID 保持一致。

### 实现身份提供程序

```csharp
// AuthIdentityProvider.cs
using System.Collections.Generic;
using Convai.Domain.Identity;

public class AuthIdentityProvider : IEndUserIdentityProvider, IEndUserMetadataProvider
{
    private readonly IAuthService _authService;

    public AuthIdentityProvider(IAuthService authService)
    {
        _authService = authService;
    }

    // 每次 ConnectAsync() 调用时执行一次 — 必须返回稳定且非空的字符串。
    public string GetEndUserId()
    {
        string userId = _authService.CurrentUserId;

        if (string.IsNullOrEmpty(userId))
            throw new System.InvalidOperationException(
                "User not authenticated. Ensure login completes before connecting to Convai.");

        return userId;
    }

    // 每次 ConnectAsync() 调用时执行一次 — 如果不需要元数据，则返回空字典。
    public IReadOnlyDictionary<string, object> GetEndUserMetadata()
    {
        return new Dictionary<string, object>
        {
            ["displayName"] = _authService.CurrentUserDisplayName ?? "Unknown",
            ["role"]        = _authService.CurrentUserRole ?? "learner",
            ["department"]  = _authService.CurrentUserDepartment ?? string.Empty
        };
    }
}
```

### 注册提供程序

根据是否还需要覆盖其他构建器设置，可以通过两种方式注册身份提供程序。

#### 直接设置（更简单）

在首次调用 `SetEndUserIdentityProvider()` 和 `SetEndUserMetadataProvider()` 之前，在 `ConvaiManager.ActiveManager` 上调用这些方法。 `ConnectAsync()` 只要尚未建立连接，这些设置方法在场景生命周期的任何阶段都可以调用。

```csharp
// AuthSceneInitializer.cs
using Convai.Runtime.Components;
using UnityEngine;

public class AuthSceneInitializer : MonoBehaviour
{
    [SerializeField] private AuthService _authService;

    private async void Start()
    {
        // 确保用户已登录后再连接 Convai。
        await _authService.EnsureLoggedInAsync();

        ConvaiManager manager = ConvaiManager.ActiveManager;
        if (manager == null)
        {
            Debug.LogError("[AuthSceneInitializer] ConvaiManager not found in scene.");
            return;
        }

        var provider = new AuthIdentityProvider(_authService);
        manager.SetEndUserIdentityProvider(provider);
        manager.SetEndUserMetadataProvider(provider);

        // 现在可以安全地连接 — 身份已解析。
        await manager.ConnectAsync();
    }
}
```

{% hint style="danger" %}
请勿调用 `ConnectAsync()` ，除非已设置身份提供程序。如果 `ConvaiManager` 配置为在 Start 时自动连接（`ConnectOnStart = true`），请禁用此选项，并在登录完成后手动触发连接。若在设置提供程序之前连接，将使用默认的基于设备的 ID，导致会话在不知情的情况下关联到错误的身份。
{% endhint %}

#### 重写 CreateRuntimeBuilder

如果还需要自定义其他构建器设置（凭据、持久化、模块），并希望将所有自定义操作集中在一处，请使用此方法。

```csharp
// AuthConvaiManager.cs
using Convai.Runtime.Components;
using Convai.Runtime.Core;

public class AuthConvaiManager : ConvaiManager
{
    private AuthService _authService;

    protected override ConvaiRuntimeBuilder CreateRuntimeBuilder()
    {
        ConvaiRuntimeBuilder builder = base.CreateRuntimeBuilder();

        // _authService must be resolved before Awake() — inject or find it here.
        _authService = FindObjectOfType<AuthService>();

        if (_authService != null)
        {
            var provider = new AuthIdentityProvider(_authService);
            builder.WithEndUserIdentityProvider(provider);
            builder.WithEndUserMetadataProvider(provider);
        }

        return builder;
    }
}
```

### 使用示例

#### 示例 1：包含学习者记录的培训平台

企业安全培训平台通过 LMS 学习者 ID 识别每位员工。过往会话的记忆（涵盖的主题、犯过的错误）会在多次模拟训练中持续保留。

```csharp
public class LmsIdentityProvider : IEndUserIdentityProvider, IEndUserMetadataProvider
{
    private readonly LmsSession _session;

    public LmsIdentityProvider(LmsSession session) => _session = session;

    public string GetEndUserId() => _session.LearnerId; // e.g., "emp-12345"

    public IReadOnlyDictionary<string, object> GetEndUserMetadata()
    {
        return new Dictionary<string, object>
        {
            ["name"]     = _session.LearnerName,
            ["courseId"] = _session.CourseId,
            ["cohort"]   = _session.CohortCode
        };
    }
}
```

通过以下方式注册： `manager.SetEndUserIdentityProvider(new LmsIdentityProvider(lmsSession))` ，然后再连接。

#### 示例 2：使用 PIN 登录的共享自助终端

医院培训自助终端由多位住院医师共用。每位住院医师通过 PIN 登录，与模拟患者互动，然后退出登录。下一位住院医师将获得一个与其自身身份关联的全新会话。

```csharp
public class KioskIdentityProvider : IEndUserIdentityProvider
{
    public static KioskIdentityProvider Instance { get; } = new();

    // Updated by the kiosk login UI before each connect.
    public string ActiveResidentId { get; set; }

    public string GetEndUserId()
    {
        if (string.IsNullOrEmpty(ActiveResidentId))
            throw new System.InvalidOperationException("No resident logged in.");

        return $"resident-{ActiveResidentId}";
    }
}
```

退出登录时：断开与 Convai 的连接，更新 `ActiveResidentId`，然后为下一位住院医师重新连接。

#### 示例 3：移动设备与桌面设备之间的跨设备连续体验

学习者在手机上开始合规培训会话，然后在桌面工作站上继续。两台设备都会从后端身份验证系统获取同一个稳定用户 ID，因此无论用户通过哪台设备连接，Convai 都能延续其记忆。

```csharp
public class BackendAuthIdentityProvider : IEndUserIdentityProvider
{
    private readonly string _stableUserId;

    // stableUserId 从后端身份验证令牌中获取（例如 JWT 的 sub 声明）。
    public BackendAuthIdentityProvider(string stableUserId)
    {
        if (string.IsNullOrEmpty(stableUserId))
            throw new System.ArgumentException("User ID must not be null or empty.", nameof(stableUserId));

        _stableUserId = stableUserId;
    }

    public string GetEndUserId() => _stableUserId;
}
```

在令牌验证后注册： `manager.SetEndUserIdentityProvider(new BackendAuthIdentityProvider(jwtSubClaim));`

### 故障排查

| 症状                                                        | 可能原因                                                     | 解决方法                                                 |
| --------------------------------------------------------- | -------------------------------------------------------- | ---------------------------------------------------- |
| 长期记忆不会跨会话保留                                               | 不同会话中的身份发生变化                                             | 连接前记录解析出的 ID，以确认其在多次运行中保持稳定。                         |
| 两个用户共享同一份记忆                                               | 不同用户解析出了相同的 ID                                           | 确保 ID 来源在整个用户群体中全局唯一。                                |
| 设置身份提供程序后，连接立即失败                                          | `GetEndUserId()` 引发异常或返回空字符串                             | 在开发期间将 `GetEndUserId()` 放入 try-catch 中；记录异常消息。       |
| `NullReferenceException` 出现在 `SetEndUserIdentityProvider` | `ConvaiManager.ActiveManager` 为 null — 管理器的 `Awake` 尚未运行 | 在 `Start()` 或之后调用 setter，切勿在 `Awake()`.              |
| 记忆累积了之前测试者或设备的数据                                          | `DeviceEndUserIdProvider` 在注册自定义提供程序之前已处于启用状态            | 在编辑器中清除 `convai.end_user_id` `PlayerPrefs` 键，然后重新连接。 |

### 后续步骤

{% content-ref url="/pages/619185ebc41c18d7fc15c71b6aaa2a22367ff0a6" %}
[长期记忆](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/features/long-term-memory.md)
{% endcontent-ref %}

{% content-ref url="/pages/fdc49f930fecd7fb00d337f46a900594f8f26fb5" %}
[自定义凭据提供程序](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/advanced-topics/custom-providers/custom-credential-provider.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/advanced-topics/custom-providers/custom-identity-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.
