Service and access token support
Use Access Tokens and Service Tokens to authenticate requests in Cloud Code modules.
Read time 5 minutesLast updated 18 hours ago
In modules, the
IExecutionContextAccessTokenServiceTokenToken type | Origin | Data access | Usage |
|---|---|---|---|
| Generated by the Authentication service. | Only the authenticated player. | The |
| Generated by Cloud Code. | Cross-player data access. | The |
Overview
Evaluate whether you want to authenticate as a player or as a trusted client. The moduleIExecutionContextAccessTokenServiceTokenAccessTokenServiceTokenAccess token support
An access token is a JWT that the Authentication service generates. You can use the access token to authenticate players. When an authenticated player calls a Cloud Code module, they pass their access token to the module as theAccessTokenIExecutionContextSupported services
To check which services support access tokens, refer to the table below:Provider | Supported services |
|---|---|
| Cloud Code C# Client SDKs | All Cloud Code C# Client SDKs support the same access tokens as their corresponding service APIs. |
| UGS Client APIs | All UGS services that support the Authentication service. |
| Cloud Code C# Admin SDKs | Not supported. Use Service Account authentication instead. |
| UGS Admin APIs | Not supported. Use Service Account authentication instead. |
Use tokens with Cloud Code C# Client SDKs
To use theAccessTokenIExecutionContext[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}"); }}
Use with UGS Client APIs
To use theAccessTokenpublic 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
A service token is a JWT that Cloud Code generates. You can use service tokens to authenticate services as Cloud Code. This is a service account token that's gone through the Token Exchange process. You can use the service token with the Cloud Code C# Client SDKs. To use it with other APIs, you need to pass it as a bearer token in the Authentication header.Supported services
For a list of services that support service tokens, refer to the table below:Provider | Supported services |
|---|---|
| Cloud Code C# Client SDKs | Refer to Available libraries for a list of available SDKs. |
| UGS Client APIs | |
| Cloud Code C# Admin SDKs | Not supported. Use Service Account authentication instead. |
| UGS Admin APIs | Not supported. Use Service Account authentication instead. |
Use tokens with Cloud Code C# Client SDKs
To use aServiceTokenIExecutionContext[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}"); }}
Use tokens with UGS Client APIs
To use aServiceToken
For example, if you define an interface for Cloud Save API, you can use the
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); }}