服务令牌和访问令牌支持
Use Access Tokens and Service Tokens to authenticate requests in Cloud Code modules.
阅读时间6 分钟最后更新于 7 个月前
在模块中, 接口提供一个 和一个 。
IExecutionContextAccessTokenServiceToken令牌类型 | 来源 | 数据访问 | 用途 |
|---|---|---|---|
| 由 Authentication 服务生成。 | 仅限经过身份验证的玩家。 | |
| 由 Cloud Code 生成。 | 跨玩家数据访问。 | |
在调用其他 UGS 服务时,您可以使用这些令牌以玩家身份或 Cloud Code 身份进行身份验证。
请参阅身份验证页面以了解更多信息。
概述
请评估您是要以玩家身份还是以受信任的客户端身份进行身份验证。
模块 接口为您提供一个 和一个 。
IExecutionContextAccessTokenServiceToken如果模块的目的是仅访问经过身份验证的玩家的数据,则应使用 以玩家身份进行身份验证来调用模块终端。这将确保玩家只能访问和处理自己的数据。
AccessToken如果模块的目的是访问跨玩家数据,则应使用 以 Cloud Code 身份进行身份验证。这将确保模块可以访问和处理跨玩家数据。但是,这为恶意玩家调用模块终端并访问非预期跨玩家数据创造了机会。为防止出现这种情况,应确保模块受到访问控制规则的保护。
ServiceToken要详细了解如何处理跨玩家数据,请参阅跨玩家数据文档。
访问令牌支持
当经过身份验证的玩家调用 Cloud Code 模块时,他们会将自己的访问令牌作为 接口的 属性传递给该模块。
IExecutionContextAccessToken您可以将访问令牌用于 Cloud Code C# Game SDK。要将访问令牌用于其他 UGS API,您需要在 Authentication 标头中将令牌作为持有者令牌传递。
支持的服务
要检查哪些服务支持访问令牌,请参阅下表:
提供者 | 支持的服务 |
|---|---|
| Cloud Code C# Client SDK | 所有 Cloud Code C# Client SDK 都与其对应的服务 API 支持相同的访问令牌。 |
| UGS Client API | 所有支持 Authentication 服务的 UGS 服务。 |
| Cloud Code C# Admin SDK | 不支持。改用服务帐户身份验证。 |
| UGS Admin API | 不支持。改用服务帐户身份验证。 |
将令牌用于 Cloud Code C# Client SDK
要将 用于 Cloud Code C# Client SDK,您需要从 接口传递令牌。
AccessTokenIExecutionContext以下示例将增加调用该模块的玩家的货币余额:
[CloudCodeFunction("IncrementBalance")]public async Task<ApiResponse<CurrencyBalanceResponse>> IncrementPlayerBalance(IGameApiClient gameApiClient, IExecutionContext ctx, string currencyId){ ... try { // Increment the balance of the currency for the player calling the module var res = await gameApiClient.EconomyCurrencies.IncrementPlayerCurrencyBalanceAsync(ctx, ctx.AccessToken, ctx.ProjectId, ctx.PlayerId, currencyId, new CurrencyModifyBalanceRequest(currencyId, 10)); _logger.LogInformation("Incremented currency {currencyId} balance by {amount}", currencyId, 10); return res; } catch (ApiException e) { _logger.LogError("Failed to increment {currencyId} balance for the player. Error: {error}", currencyId, e.Message); throw new Exception($"Failed to increment {currencyId} balance for playerId {ctx.PlayerId}. Error: {e.Message}"); }}
用于 UGS Client API
要将 用于 UGS Client API,请在 Authentication 标头中将令牌作为持有者令牌传递。
AccessTokenpublic class Relationships{ private readonly RestClient _httpClient; public Relationships() { _httpClient = new RestClient("https://social.services.api.unity.com/v1/relationships"); } public async Task<List<RelationshipsApiResponse?>> GetRelationships(IExecutionContext context) { var request = new RestRequest() { // Pass the access token as a bearer token in the header Authenticator = new JwtAuthenticator(context.AccessToken) }; .... }}
服务令牌支持
您可以将服务令牌用于 Cloud Code C# Client SDK。要将其用于其他 API,您需要在 Authentication 标头中将其作为持有者令牌传递。
支持的服务
如需查看支持服务令牌的服务列表,请参阅下表:
提供者 | 支持的服务 |
|---|---|
| Cloud Code C# Client SDK | 请参阅可用库以查看可用 SDK 的列表。 |
| UGS Client API | |
| Cloud Code C# Admin SDK | 不支持。改用服务帐户身份验证。 |
| UGS Admin API | 不支持。改用服务帐户身份验证。 |
将令牌用于 Cloud Code C# Client SDK
要将 用于 Cloud Code C# Client SDK,请从 接口传递令牌。
ServiceTokenIExecutionContext以下示例接受一个玩家 ID 并增加该玩家的货币余额:
[CloudCodeFunction("IncrementBalance")]public async Task<ApiResponse<CurrencyBalanceResponse>> IncrementPlayerBalance(IGameApiClient gameApiClient, IExecutionContext ctx, string currencyId, string playerId){ ... try { // Increment the balance of the currency for the player ID passed in, authenticated as Cloud Code var res = await gameApiClient.EconomyCurrencies.IncrementPlayerCurrencyBalanceAsync(ctx, ctx.ServiceToken, ctx.ProjectId, playerId, currencyId, new CurrencyModifyBalanceRequest(currencyId, 10)); _logger.LogInformation("Incremented currency {currencyId} balance by {amount}", currencyId, 10); return res; } catch (ApiException e) { _logger.LogError("Failed to increment {currencyId} balance for the player. Error: {error}", currencyId, e.Message); throw new Exception($"Failed to increment {currencyId} balance for playerId {ctx.PlayerId}. Error: {e.Message}"); }}
将令牌用于 UGS Client API
要将 用于 UGS Client API,请在 Authentication 标头中将令牌作为持有者令牌传递。
ServiceToken例如,如果您为 Cloud Save API 定义了一个接口,则可以使用 进行身份验证并处理跨玩家数据。以下示例接受一个玩家 ID 并返回为该玩家存储的所有数据:
ServiceTokenusing System.Net;using Unity.Services.CloudCode.Core;using Newtonsoft.Json;using RestSharp;using RestSharp.Authenticators;namespace ExampleModule;public interface ICloudSaveData{ public Task<CloudSaveResponse?> GetData(IExecutionContext context, string playerId);}public class CloudSaveResponse{ public CloudSaveItem[] Results { get; set; }}public class CloudSaveItem{ public string Key { get; set; } public object Value { get; set; }}public class CloudSaveData : ICloudSaveData{ private readonly RestClient _httpClient; public async Task<CloudSaveResponse?> GetData(IExecutionContext context, string playerId) { var request = new RestRequest($"v1/data/projects/{context.ProjectId}/players/{playerId}/items") { // Authenticate as Cloud Code to interact with cross-player data Authenticator = new JwtAuthenticator(context.ServiceToken) }; // Pass through the analytics user id and Unity installation id to the service. if (context.AnalyticsUserId != null) request = request.AddHeader("analytics-user-id", context.AnalyticsUserId); if (context.UnityInstallationId != null) request = request.AddHeader("unity-installation-id", context.UnityInstallationId); RestResponse response = await _httpClient.ExecuteGetAsync(request); if (response.Content == null) throw new Exception("Failed to load data from Cloud Save: Content was null"); if (response.StatusCode != HttpStatusCode.OK) throw new Exception("Failed to load data from Cloud Save: " + response.Content); return JsonConvert.DeserializeObject<CloudSaveResponse>(response.Content); }}