기술 자료

지원

Cloud Code

Cloud Code

서비스 및 액세스 토큰 지원

Use Access Tokens and Service Tokens to authenticate requests in Cloud Code modules.
읽는 시간 3분최근 업데이트: 12시간 전

모듈에서
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 서비스 생성하는 JWT입니다. 액세스 토큰을 사용하여 플레이어를 인증할 수 있습니다. 인증된 플레이어가 Cloud Code 모듈을 호출하면, 플레이어의 액세스 토큰을
IExecutionContext
인터페이스의
AccessToken
프로퍼티로 모듈에 전달합니다.
Cloud Code C# Game SDK로 액세스 토큰을 사용할 수 있습니다. 다른 UGS API에서 액세스 토큰을 사용하려면, 인증 헤더에서 토큰을 bearer 토큰으로 전달해야 합니다.

지원되는 서비스

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

제공자

지원되는 서비스

Cloud Code C# Client SDK모든 Cloud Code C# Client SDK는 해당 서비스 API와 동일한 액세스 토큰을 지원합니다.
UGS 클라이언트 APIAuthentication 서비스를 지원하는 모든 UGS 서비스를 지원합니다.
Cloud Code C# Admin SDK지원되지 않습니다. 대신 서비스 계정 인증을 사용하십시오.
UGS 관리자 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 클라이언트 API로 사용

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

지원되는 서비스

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

제공자

지원되는 서비스

Cloud Code C# Client SDK사용할 수 있는 SDK 목록은 사용 가능한 라이브러리를 참고하십시오.
UGS 클라이언트 API
Cloud Code C# Admin SDK지원되지 않습니다. 대신 서비스 계정 인증을 사용하십시오.
UGS 관리자 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 클라이언트 API로 토큰 사용

UGS 클라이언트 API로
ServiceToken
을 사용하려면 인증 헤더에 토큰을 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); }}