サービスとアクセストークンのサポート
Use Access Tokens and Service Tokens to authenticate requests in Cloud Code modules.
読み終わるまでの所要時間 4 分最終更新 23日前
モジュールでは、
IExecutionContextAccessTokenServiceTokenトークンタイプ | 発生元 | データアクセス | 使用方法 |
|---|---|---|---|
| Authentication サービス によって生成されます。 | 認証されたプレイヤーのみ。 | |
| Cloud Code によって生成されます。 | クロスプレイヤーデータアクセス。 | |
概要
プレイヤーと信頼されているクライアントのどちらとして認証するかを評価します。 モジュールのIExecutionContextAccessTokenServiceTokenAccessTokenServiceTokenアクセストークンのサポート
アクセストークンは、Authentication サービス (https://docs.unity.com/ugs/manual/authentication/manual/use-anon-sign-in) によって生成される JWT です。アクセストークンを使用して、プレイヤーを認証できます。 認証されたプレイヤーが Cloud Code モジュールを呼び出す場合、アクセストークンをIExecutionContextAccessTokenサポートされているサービス
どのサービスがアクセストークンをサポートするかを確認するには、以下の表を参照してください。プロバイダー | サポートされているサービス |
|---|---|
| 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 で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 が生成する 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 でServiceTokenIExecutionContext[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
例えば、Cloud Save API のインターフェースを定義する場合は、
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); }}