Service and access token support

In scripts, the context object provides an accessToken and a serviceToken:

Token typeOriginData accessUsage
accessTokenGenerated by the Authentication service.Only the authenticated player.The AccessToken is the JWT you use to authenticate a Cloud Code call. You can pass the token on to other UGS services to access data for the authenticated player.
serviceTokenGenerated by Cloud Code.Cross-player data access.The ServiceToken is a the token you use to call out to other UGS services and interact with cross-player data.

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 context object provides you with a accessToken and a serviceToken.

If the purpose of the script is to only access the data of the authenticated player, you should use the accessToken to authenticate as the player calling the script. This ensures that the player can only access and interact with their own data.

If the purpose of the script is to access cross-player data, you should use the serviceToken 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.

To 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 AccessToken property of the context object.

You 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 accessToken.

Supported services

To check which services support access tokens, refer to the table below:

ProviderSupported services
Cloud Code JavaScript SDKsAll Cloud Code JavaScript SDKs that are onboarded with the Authentication service.
UGS Client APIsAll UGS services that have onboarded with the Authentication service.
UGS Admin APIsNot supported. Use Service Account authentication instead.

Note: Most UGS services are onboarded with the Authentication service and support access tokens.

Use tokens with Cloud Code JavaScript SDKs

To use the accessToken with the Cloud Code JavaScript SDKs, you need to pass the token from the context object.

Note: By default, the Cloud Code JavaScript SDKs use the serviceToken from the context object. You need to explicitly pass the accessToken to the SDKs constructor to use it.

The 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 accessToken with the UGS Client APIs, pass the token as a bearer token in the Authentication header.

Note: If the service you want to call provides a Cloud Code JavaScript SDK, you can use the SDK instead of calling the service API directly. For a list of available SDKs, refer to the Cloud Code Services SDK page.

The 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

For a list of services that support service tokens, refer to the table below:

ProviderSupported services
Cloud Code JavaScript SDKs
UGS Client APIs
UGS Admin APIsNot 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 serviceToken with the Cloud Code JavaScript SDKs, pass the token from the context object.

The 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 serviceToken with the UGS Client APIs, pass the token as a bearer token in the Authentication header.

Note: If the service you call provides a Cloud Code C# SDK, you can use the SDK instead of calling the service API directly. For a list of available SDKs, refer to the Available libraries page.

For example, if you call out to the Cloud Save API, you can use the serviceToken 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:

JavaScript

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;
  }
};