自定义 ID 登录

SDK 最低版本:3.1.0

本文将引导您完成以下场景,为您游戏中使用自定义令牌的玩家设置身份验证:

  • 设置自定义 ID 提供商登录。
  • 回归用户登录或创建新用户。

要为您的游戏玩家提供自定义 ID 登录选项,请对您的应用进行设置以启用自定义 ID 提供商登录。

设置自定义 ID 登录

  1. 添加自定义 ID 作为 Unity 的 ID 提供商:

    1. 在 Unity 编辑器菜单中,访问 Edit(编辑)> Project Settings…(项目设置…),然后从导航菜单中选择 Services(服务)> Authentication(身份验证)
    2. 将 **ID Providers(ID 提供商)**设置为 Custom(自定义),然后选择 Add(添加)
  2. 创建服务帐户并添加项目角色 Player Authentication Token Issuer(玩家身份验证令牌颁发者)

回归玩家登录或创建新玩家

  1. 要使用自定义 ID 身份验证解决方案让玩家登录,您必须向自己的游戏服务器发出请求,以请求 Unity Authentication 服务访问令牌会话令牌

    在游戏服务器上:

    1. 调用 Token Exchange API 以获取无状态令牌。
    2. 调用使用自定义 ID 登录 API
  2. 使用从游戏服务器获取的访问令牌会话令牌来调用 ProcessAuthenticationTokens API。

处理身份验证令牌

ProcessAuthenticationTokens 用于处理 Unity Authentication 服务访问令牌,并使这些令牌可供游戏中集成的其他需要玩家进行身份验证的 UGS SDK 使用。由于访问令牌会到期,因此必须手动刷新访问令牌并使用新的访问令牌调用 ProcessAuthenticationTokens。您可以使用访问令牌和会话令牌来调用 ProcessAuthenticationTokens。Unity Authentication SDK 会在访问令牌到期之前刷新令牌,保持玩家会话处于活动状态,并允许登录缓存的玩家

using Unity.Services.Authentication;

void SignUserWithCustomTokenWithAutoRefresh()
{
    try
    {
        // Check if a cached player already exists by checking if the session token exists
        if (AuthenticationService.Instance.SessionTokenExists) 
        {
            // This call will sign in the cached player.
            await AuthenticationService.Instance.SignInAnonymouslyAsync();
            Debug.Log("Cached user sign in succeeded!");
        }
        else
        {
            var userTokens = // Fetch the user tokens using your method calls
            AuthenticationService.Instance.ProcessAuthenticationTokens(userTokens.AccessToken, userTokens.SessionToken)
        }
        // Shows how to get the playerID
        Debug.Log($"PlayerID: {AuthenticationService.Instance.PlayerId}");   
    }
    catch (AuthenticationException ex)
    {
        // Compare error code to AuthenticationErrorCodes
        // Notify the player with the proper error message
        Debug.LogException(ex);
    }
    catch (RequestFailedException ex)
    {
        // Compare error code to CommonErrorCodes
        // Notify the player with the proper error message
        Debug.LogException(ex);
    } 
    catch (Exception ex) {
        // Handle exceptions from your method call
        Debug.LogException(ex);
    }
}

请注意代码样本仅描述了一种方法,而不代表一类方法。