ドキュメント

サポート

Cloud Code

サービスとアクセストークンのサポート

Use Access Tokens and Service Tokens to authenticate requests in Cloud Code modules.
読み終わるまでの所要時間 4 分最終更新 23日前

モジュールでは、
IExecutionContext
インターフェースは
AccessToken
ServiceToken
を提供します。

トークンタイプ

発生元

データアクセス

使用方法

accessToken
Authentication サービス によって生成されます。認証されたプレイヤーのみ。
AccessToken
は、Cloud Code 呼び出しを認証するために使用する JWT です。他の UGS サービスにトークンを渡して、認証されたプレイヤーのデータにアクセスできます。
serviceToken
Cloud Code によって生成されます。クロスプレイヤーデータアクセス。
ServiceToken
は、他の UGS サービスを呼び出し、クロスプレイヤーデータを操作するために使用するトークンです。
他の UGS サービスを呼び出す場合、これらのトークンではプレイヤーまたは Cloud Code として認証できます。 詳細については、認証 のページを参照してください。

概要

プレイヤーと信頼されているクライアントのどちらとして認証するかを評価します。 モジュールの
IExecutionContext
インターフェースは
AccessToken
ServiceToken
を提供します。
モジュールの目的が認証されたプレイヤーのデータにアクセスすることだけである場合は、
AccessToken
を使用して、モジュールエンドポイントを呼び出すプレイヤーとして認証する必要があります。これにより、プレイヤーがアクセスして操作できるのは自分のデータのみであることが保証されます。
モジュールの目的がクロスプレイヤーデータにアクセスすることである場合は、
ServiceToken
を使用して Cloud Code として認証する必要があります。これにより、モジュールがクロスプレイヤーデータにアクセスして操作できることが保証されます。ただし、これにより穴が開けられ、悪意のあるプレイヤーがモジュールエンドポイントを呼び出したり、意図していないクロスプレイヤーデータにアクセスしたりできるようになります。これを防ぐには、モジュールが アクセス制御 ルールで保護されていることを確認する必要があります。
クロスプレイヤーデータの操作方法の詳細については、クロスプレイヤーデータ のドキュメントを参照してください。

アクセストークンのサポート

アクセストークンは、Authentication サービス (https://docs.unity.com/ugs/manual/authentication/manual/use-anon-sign-in) によって生成される JWT です。アクセストークンを使用して、プレイヤーを認証できます。 認証されたプレイヤーが Cloud Code モジュールを呼び出す場合、アクセストークンを
IExecutionContext
インターフェースの
AccessToken
プロパティとしてモジュールに渡します。
Cloud Code C# Game SDK でアクセストークンを使用できます。他の UGS API でアクセストークンを使用するには、Authentication ヘッダーでトークンを Bearer トークンとして渡します。

サポートされているサービス

どのサービスがアクセストークンをサポートするかを確認するには、以下の表を参照してください。

プロバイダー

サポートされているサービス

Cloud Code C# Client SDKすべての Cloud Code C# Client SDK が対応するサービス API と同じアクセストークンをサポートします。
UGS Client APIAuthentication サービスをサポートするすべての UGS サービス。
Cloud Code C# Admin SDKサポートされていません。かわりに サービスアカウント認証 を使用します。
UGS Admin APIサポートされていません。かわりに サービスアカウント認証 を使用します。

Cloud Code C# Client SDK でのトークンの使用

Cloud Code C# Client SDK で
AccessToken
を使用するには、
IExecutionContext
インターフェースからトークンを渡す必要があります。
以下の例は、モジュールを呼び出すプレイヤーの通貨残高を増やします。
[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 で
AccessToken
を使用するには、Authentication ヘッダーでトークンを Bearer トークンとして渡します。
public 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 が生成する JWT です。サービストークンを使用して、サービスを Cloud Code として認証できます。これは、トークン交換 プロセスをたどるサービスアカウントトークンです。 Cloud Code C# Client SDK でサービストークンを使用できます。他の API で使用するには、Authentication ヘッダーで Bearer トークンとして渡します。

サポートされているサービス

サービストークンをサポートするサービスのリストについては、以下の表を参照してください。

プロバイダー

サポートされているサービス

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 で
ServiceToken
を使用するには、
IExecutionContext
インターフェースからトークンを渡します。
以下の例は、プレイヤー 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 で
ServiceToken
を使用するには、Authentication ヘッダーでトークンを Bearer トークンとして渡します。
例えば、Cloud Save API のインターフェースを定義する場合は、
ServiceToken
を使用してクロスプレイヤーデータを認証し、操作できます。以下の例は、プレイヤー ID を受け取り、そのプレイヤーについて格納されているすべてのデータを返します。
using 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); }}