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

> Use Access Tokens and Service Tokens to authenticate requests in Cloud Code modules.

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

| トークンタイプ        | 発生元                                                                    | データアクセス          | 使用方法                                                                                             |
| -------------- | ---------------------------------------------------------------------- | ---------------- | ------------------------------------------------------------------------------------------------ |
| `accessToken`  | [Authentication サービス](/authentication/use-anon-sign-in.md) によって生成されます。 | 認証されたプレイヤーのみ。    | `AccessToken` は、Cloud Code 呼び出しを認証するために使用する JWT です。他の UGS サービスにトークンを渡して、認証されたプレイヤーのデータにアクセスできます。 |
| `serviceToken` | Cloud Code によって生成されます。                                                 | クロスプレイヤーデータアクセス。 | `ServiceToken` は、他の UGS サービスを呼び出し、クロスプレイヤーデータを操作するために使用するトークンです。                                 |

他の UGS サービスを呼び出す場合、これらのトークンではプレイヤーまたは Cloud Code として認証できます。

詳細については、[認証](./authentication.md) のページを参照してください。

## 概要##overview

プレイヤーと信頼されているクライアントのどちらとして認証するかを評価します。

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

モジュールの目的が認証されたプレイヤーのデータにアクセスすることだけである場合は、`AccessToken` を使用して、モジュールエンドポイントを呼び出すプレイヤーとして認証する必要があります。これにより、プレイヤーがアクセスして操作できるのは自分のデータのみであることが保証されます。

モジュールの目的がクロスプレイヤーデータにアクセスすることである場合は、`ServiceToken` を使用して Cloud Code として認証する必要があります。これにより、モジュールがクロスプレイヤーデータにアクセスして操作できることが保証されます。ただし、これにより穴が開けられ、悪意のあるプレイヤーがモジュールエンドポイントを呼び出したり、意図していないクロスプレイヤーデータにアクセスしたりできるようになります。これを防ぐには、モジュールが [アクセス制御](./access-control.md) ルールで保護されていることを確認する必要があります。

クロスプレイヤーデータの操作方法の詳細については、[クロスプレイヤーデータ](./cross-player-data.md) のドキュメントを参照してください。

## アクセストークンのサポート##access-token-support

アクセストークンは、[Authentication サービス](/authentication/use-anon-sign-in.md) ([/authentication/use-anon-sign-in](/authentication/use-anon-sign-in.md)) によって生成される [JWT](https://jwt.io/) です。アクセストークンを使用して、プレイヤーを認証できます。

認証されたプレイヤーが Cloud Code モジュールを呼び出す場合、アクセストークンを `IExecutionContext` インターフェースの `AccessToken` プロパティとしてモジュールに渡します。

Cloud Code C# Game SDK でアクセストークンを使用できます。他の UGS API でアクセストークンを使用するには、Authentication ヘッダーでトークンを Bearer トークンとして渡します。

### サポートされているサービス##supported-services

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

| プロバイダー                   | サポートされているサービス                                                                                         |
| ------------------------ | ----------------------------------------------------------------------------------------------------- |
| Cloud Code C# Client SDK | すべての Cloud Code C# Client SDK が対応するサービス API と同じアクセストークンをサポートします。                                      |
| UGS Client API           | Authentication サービスをサポートするすべての UGS サービス。                                                              |
| Cloud Code C# Admin SDK  | サポートされていません。かわりに [サービスアカウント認証](./authentication.md#cloud-code-admin-api-basic-authentication) を使用します。 |
| UGS Admin API            | サポートされていません。かわりに [サービスアカウント認証](./authentication.md#cloud-code-admin-api-basic-authentication) を使用します。 |

> **Note:**
>
> **ノート**: ほとんどの UGS サービスは Authentication サービスにオンボードされ、アクセストークンをサポートします。

### Cloud Code C# Client SDK でのトークンの使用##use-tokens-with-cloud-code-c-client-sdks

Cloud Code C# Client SDK で `AccessToken` を使用するには、`IExecutionContext` インターフェースからトークンを渡す必要があります。

以下の例は、モジュールを呼び出すプレイヤーの通貨残高を増やします。

```csharp
[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 での使用##use-with-ugs-client-apis

UGS Client API で `AccessToken` を使用するには、Authentication ヘッダーでトークンを Bearer トークンとして渡します。

> **Note:**
>
> **ノート**: 呼び出すサービスで Cloud Code C# SDK が提供される場合は、サービス API を直接呼び出すかわりに SDK を使用できます。使用可能な SDK のリストについては、[利用可能なライブラリ](../reference/available-libraries) のページを参照してください。

```csharp
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)
        };

        ....
    }

}
```

## サービストークンのサポート##service-token-support

サービストークンは、Cloud Code が生成する [JWT](https://jwt.io/) です。サービストークンを使用して、サービスを Cloud Code として認証できます。これは、[トークン交換](./authentication.md#cloud-code-client-api-bearer-authentication) プロセスをたどるサービスアカウントトークンです。

Cloud Code C# Client SDK でサービストークンを使用できます。他の API で使用するには、Authentication ヘッダーで Bearer トークンとして渡します。

### サポートされているサービス##supported-services

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

| プロバイダー                   | サポートされているサービス                                                                                                                                                                                               |
| ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Cloud Code C# Client SDK | 使用可能な SDK のリストについては、[利用可能なライブラリ](../reference/available-libraries) を参照してください。                                                                                                                               |
| UGS Client API           | [Cloud Save][Cloud Save Client API][Economy][Economy Client API][Leaderboards][Leaderboards Client API] [Lobby][Lobby Client API][Player Names][Player Names Client API][Matchmaker][Matchmaker Client API] |
| Cloud Code C# Admin SDK  | サポートされていません。かわりに [サービスアカウント認証](./authentication.md#cloud-code-admin-api-basic-authentication) を使用します。                                                                                                       |
| UGS Admin API            | サポートされていません。かわりに [サービスアカウント認証](./authentication.md#cloud-code-admin-api-basic-authentication) を使用します。                                                                                                       |

> **Note:**
>
> **ノート:** Cloud Code C# Client SDK のドキュメントはまだ作業中です。現段階では、類似の構造を持つ [JavaScript ドキュメント](../../scripts/how-to-guides/unity-services-integration) を参照できます。IDE のオートコンプリートと intellisense 機能も利用してください。

[Cloud Save Client API]: https://services.docs.unity.com/cloud-save/v1/

[Economy Client API]: https://services.docs.unity.com/economy/v2/

[Leaderboards Client API]: https://services.docs.unity.com/leaderboards/v1/

[Lobby Client API]: https://services.docs.unity.com/lobby/v1/

[Player Names Client API]: https://services.docs.unity.com/player-names/v1/

[Matchmaker Client API]: https://services.docs.unity.com/matchmaker/v2/

### Cloud Code C# Client SDK でのトークンの使用##use-tokens-with-cloud-code-c-client-sdks

Cloud Code C# Client SDK で `ServiceToken` を使用するには、`IExecutionContext` インターフェースからトークンを渡します。

以下の例は、プレイヤー ID を受け取り、そのプレイヤーの通貨の残高を増やします。

```csharp
[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 でのトークンの使用##use-tokens-with-ugs-client-apis

UGS Client API で `ServiceToken` を使用するには、Authentication ヘッダーでトークンを Bearer トークンとして渡します。

> **Note:**
>
> **ノート:** 呼び出すサービスで Cloud Code C# SDK が提供される場合は、サービス API を直接呼び出すかわりに SDK を使用できます。使用可能な SDK のリストについては、[利用可能なライブラリ](../reference/available-libraries) のページを参照してください。

例えば、Cloud Save API のインターフェースを定義する場合は、`ServiceToken` を使用してクロスプレイヤーデータを認証し、操作できます。以下の例は、プレイヤー ID を受け取り、そのプレイヤーについて格納されているすべてのデータを返します。

```csharp
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);
    }
}
```

> **Note:**
>
> **ノート:** Cloud Code は、Cloud Save データを操作するために使用できる Cloud Save C# SDK を提供します。上記のサンプルは、`ServiceToken` を使用して他の UGS サービスを認証する方法を示します。
