Service and access token support
Use Access Tokens and Service Tokens to authenticate requests in Cloud Code scripts.
Read time 5 minutesLast updated 4 days ago
In scripts, the object provides an and a :
contextaccessTokenserviceTokenToken type | Origin | Data access | Usage |
|---|---|---|---|
| Generated by the Authentication service. | Only the authenticated player. | The |
| Generated by Cloud Code. | Cross-player data access. | The |
You can authenticate as a player or as Cloud Code with these tokens when you call other UGS services.
Refer to Authentication page for more information.
Overview
Evaluate whether you want to authenticate as a player or as a trusted client.
The script object provides you with a and a .
contextaccessTokenserviceTokenIf the purpose of the script is to only access the data of the authenticated player, you should use the to authenticate as the player calling the script. This ensures that the player can only access and interact with their own data.
accessTokenIf the purpose of the script is to access cross-player data, you should use the to authenticate as Cloud Code. This will ensure that the script can access and interact with cross-player data.
However, this creates an opening for malicious players to call the script and access cross-player data where not intended. To prevent this, you should ensure that the module is protected with Access Control rules.
serviceTokenTo learn more about how you can interact with cross-player data, refer to the Cross-player data documentation.
Access 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 object.
AccessTokencontextYou can use the access token with the Cloud Code JavaScript SDKs. To use access tokens with other UGS APIs, you need to pass the token as a bearer token in the Authentication header.
Any configured Access Control rules affect the .
accessTokenSupported services
To check which services support access tokens, refer to the table below:
Provider | Supported services |
|---|---|
| Cloud Code JavaScript SDKs | All Cloud Code JavaScript SDKs that are onboarded with the Authentication service. |
| UGS Client APIs | All UGS services that have onboarded with the Authentication service. |
| UGS Admin APIs | Not supported. Use Service Account authentication instead. |
Use tokens with Cloud Code JavaScript SDKs
To use the with the Cloud Code JavaScript SDKs, you need to pass the token from the object.
accessTokencontextThe example below increments the currency balance for the player that calls the script. It takes in currency ID as a parameter.
JavaScript
const { CurrenciesApi } = require("@unity-services/economy-2.4");module.exports = async ({ params, context, logger }) => { const { projectId, playerId, accessToken } = context; const { currencyId } = params; // Use the accessToken from the context object to authenticate the call as the player const currencies = new CurrenciesApi({accessToken}); try { const result = await currencies.incrementPlayerCurrencyBalance({ projectId, playerId, currencyId, currencyModifyBalanceRequest: { amount: 10 } }); return result.data; } catch (err) { logger.error("Failed to update currency balance", {"error.message": err.message}, {"currencyId" : currencyId}); throw err; }}
Use tokens with UGS Client APIs
To use the with the UGS Client APIs, pass the token as a bearer token in the Authentication header.
accessTokenThe example below retrieves the list of friends for the player that calls the script:
JavaScript
const axios = require("axios-0.21");module.exports = async ({ params, context, logger }) => { const config = { headers: { 'Content-Type': 'application/json', // Pass the accessToken from the context object as a bearer token Authorization: `Bearer ${context.accessToken}` } }; try { const friendsGetUrl = `https://social.services.api.unity.com/v1/relationships?type=FRIEND_REQUEST` var res = await axios.get(friendsGetUrl, config); return res.data; } catch (err) { logger.error("Failed to retrieve Friends", {"error.message": err.message}); throw err; }};
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 had gone through the Token Exchange process.
You can use the service token with the Cloud Code Javascript SDKs. To use it with other APIs, you need to pass it as a bearer token in the Authentication header.
For more information, refer to the Authentication documentation.
Supported services
The following providers support service tokens:
Cloud Code JavaScript SDKs
UGS Client APIs
UGS Admin APIs
Not supported. Use Service Account authentication instead.
For more information, refer to the Cloud Code Services SDKs documentation.
Use tokens with Cloud Code JavaScript SDKs
To use a with the Cloud Code JavaScript SDKs, pass the token from the object.
serviceTokencontextThe example below takes in a player ID and a currency ID as parameters and increments the balance of a currency for that player:
JavaScript
const { CurrenciesApi } = require("@unity-services/economy-2.4");module.exports = async ({ params, context, logger }) => { const { projectId } = context; const { playerId, currencyId } = params; // By default, the Cloud Code JavaScript SDKs use the serviceToken from the context object const currencies = new CurrenciesApi(context); try { const result = await currencies.incrementPlayerCurrencyBalance({ projectId, playerId, currencyId, currencyModifyBalanceRequest: { amount: 10 } }); return result.data; } catch (err) { logger.error("Failed to update currency balance", {"error.message": err.message}, {"currencyId" : currencyId}); throw err; }}
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 call out to the Cloud Save API, you can use the to authenticate and interact with cross-player data.
The example below takes in a player ID as a function parameter, records a new value and returns all the data stored for that player:
serviceTokenJavaScript
const axios = require("axios-0.21");module.exports = async ({ params, context, logger }) => { const config = { headers: { 'Content-Type': 'application/json', // Authenticate as Cloud Code using the serviceToken from the context object Authorization: `Bearer ${context.serviceToken}` } }; let result; try { const cloudSaveUrl = `https://cloud-save.services.api.unity.com/v1/data/projects/${context.projectId}/players/${params.playerId}/items` const payload = { key : "test", value: "test" }; await axios.post(cloudSaveUrl, payload, config); result = await axios.get(cloudSaveUrl, config); return result.data; } catch (err) { logger.error("Failed to call out to Cloud Save", {"error.message": err.message}); throw err; }};