# 서비스 및 액세스 토큰 지원

> 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) 생성하는 [JWT](https://jwt.io/)입니다. 액세스 토큰을 사용하여 플레이어를 인증할 수 있습니다.

인증된 플레이어가 Cloud Code 모듈을 호출하면, 플레이어의 액세스 토큰을 `IExecutionContext` 인터페이스의 `AccessToken` 프로퍼티로 모듈에 전달합니다.

Cloud Code C# Game SDK로 액세스 토큰을 사용할 수 있습니다. 다른 UGS API에서 액세스 토큰을 사용하려면, 인증 헤더에서 토큰을 bearer 토큰으로 전달해야 합니다.

### 지원되는 서비스##supported-services

액세스 토큰을 지원하는 서비스를 확인하려면 아래 표를 참고하십시오.

| 제공자                      | 지원되는 서비스                                                                                          |
| ------------------------ | ------------------------------------------------------------------------------------------------- |
| Cloud Code C# Client SDK | 모든 Cloud Code C# Client SDK는 해당 서비스 API와 동일한 액세스 토큰을 지원합니다.                                       |
| UGS 클라이언트 API            | Authentication 서비스를 지원하는 모든 UGS 서비스를 지원합니다.                                                       |
| Cloud Code C# Admin SDK  | 지원되지 않습니다. 대신 [서비스 계정 인증](./authentication.md#cloud-code-admin-api-basic-authentication)을 사용하십시오. |
| UGS 관리자 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 클라이언트 API로 사용##use-with-ugs-client-apis

UGS 클라이언트 API로 `AccessToken`을 사용하려면 인증 헤더에 토큰을 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로 서비스 토큰을 사용하려면 인증 헤더에서 토큰을 bearer 토큰으로 전달해야 합니다.

### 지원되는 서비스##supported-services

서비스 토큰을 지원하는 서비스 목록은 아래 표를 참고하십시오.

| 제공자                      | 지원되는 서비스                                                                                                                                                                                                    |
| ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Cloud Code C# Client SDK | 사용할 수 있는 SDK 목록은 [사용 가능한 라이브러리](../reference/available-libraries)를 참고하십시오.                                                                                                                                  |
| UGS 클라이언트 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 관리자 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 클라이언트 API로 토큰 사용##use-tokens-with-ugs-client-apis

UGS 클라이언트 API로 `ServiceToken`을 사용하려면 인증 헤더에 토큰을 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 서비스로 인증하는 방법을 보여 줍니다.
