서비스 및 액세스 토큰 지원
Use Access Tokens and Service Tokens to authenticate requests in Cloud Code modules.
읽는 시간 3분최근 업데이트: 12시간 전
모듈에서
IExecutionContextAccessTokenServiceToken토큰 유형 | 출처 | 데이터 액세스 | 사용 |
|---|---|---|---|
| Authentication 서비스 에서 생성 | 인증된 플레이어만 | |
| Cloud Code에서 생성 | 크로스 플레이어 데이터 액세스 | |
개요
플레이어로 인증할지 신뢰할 수 있는 클라이언트로 인증할지 평가합니다. 모듈IExecutionContextAccessTokenServiceTokenAccessTokenServiceToken액세스 토큰 지원
액세스 토큰은 Authentication 서비스 생성하는 JWT입니다. 액세스 토큰을 사용하여 플레이어를 인증할 수 있습니다. 인증된 플레이어가 Cloud Code 모듈을 호출하면, 플레이어의 액세스 토큰을IExecutionContextAccessToken지원되는 서비스
액세스 토큰을 지원하는 서비스를 확인하려면 아래 표를 참고하십시오.제공자 | 지원되는 서비스 |
|---|---|
| Cloud Code C# Client SDK | 모든 Cloud Code C# Client SDK는 해당 서비스 API와 동일한 액세스 토큰을 지원합니다. |
| UGS 클라이언트 API | Authentication 서비스를 지원하는 모든 UGS 서비스를 지원합니다. |
| Cloud Code C# Admin SDK | 지원되지 않습니다. 대신 서비스 계정 인증을 사용하십시오. |
| UGS 관리자 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 클라이언트 API로 사용
UGS 클라이언트 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로 서비스 토큰을 사용하려면 인증 헤더에서 토큰을 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로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 클라이언트 API로 토큰 사용
UGS 클라이언트 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); }}