Service and access token support
Use Access Tokens and Service Tokens to authenticate requests in Cloud Code modules.
Read time 6 minutesLast updated 3 days ago
In modules, the interface provides an and a . Use these tokens to authenticate as the calling player or as Cloud Code when you call other UGS services.
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 |
Use the to authenticate as the player who called the module endpoint, so the player can only access their own data. Use the to authenticate as Cloud Code and access cross-player data. Because an endpoint that uses the can reach cross-player data, protect it with Access Control rules to prevent unauthorized access. For more information, refer to Cross-player data and Authentication.
AccessTokenServiceTokenServiceTokenAccess 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 the property of the interface.
AccessTokenIExecutionContextYou can use access tokens with the Cloud Code C# Game SDKs. To use access tokens with other UGS APIs, you need to pass the token as a bearer token in the Authentication header.
Supported 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 the with the Cloud Code C# Client SDKs, you need to pass the token from the interface.
AccessTokenIExecutionContextThe example below increments the currency balance for the player that calls the module:
[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 the with the UGS Client APIs, pass the token as a bearer token in the Authentication header.
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) }; .... }}
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 Save, Economy, Leaderboards, Lobby, Player Names, Matchmaker |
| 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 a with the Cloud Code C# Client SDKs, pass the token from the interface.
ServiceTokenIExecutionContextThe example below takes in a player ID and increments the balance of a currency for that player:
[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 a with the UGS Client APIs, pass the token as a bearer token in the Authentication header.
ServiceTokenFor example, if you define an interface for Cloud Save API, you can use the to authenticate and interact with cross-player data.
The example below takes in a player ID and returns all the data stored for that player:
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); }}