ドキュメント

Unity Services Web APIs

Open Unity Dashboard

Unity Services Web APIs

Client authentication

Learn how to authenticate client APIs using Unity Authentication, including anonymous, username-password, code linking, custom ID, and platform-specific authentication.
読み終わるまでの所要時間 35 分最終更新 1ヶ月前

Client APIs are endpoints that allow you to access Unity Services as a Unity project user. These endpoints are called inside the project after a user has performed an action.
To authenticate with client APIs, you must use the Unity Authentication service. This service provides anonymous and platform-specific authentication solutions for client APIs.
注意
By using the Unity Authentication service, you agree that you have read and accepted the Terms of Service.
注意
The Digital Services Act (DSA) requires Unity to notify our customers' end users in the unlikely event that Unity takes an action which impacts those end users under the DSA. To comply with this end user notification requirement, we developed a new notification API. If you use Unity Gaming Services (UGS) products that rely on the Unity Authentication Service, you need to integrate the new notification API by the effective date of the DSA, February 17, 2024. The following API is ready for adoption in late January 2024.
Please refer to our DSA compliance efforts for more information about our DSA compliance efforts.
And here for how to make your game compliant.
Unity Authentication is currently supported for the following Unity Gaming Services:

Overview

Unity Authentication supports authenticating players via anonymous authentication and with Platform-Specific authentication.

How it works

When a returning or new player logs into your app, Unity Authentication generates the following tokens and Id:
  • PlayerId: The PlayerId is the main identifier for Unity Authentication end players, identifying returning and new players. It's unique per Unity Project. It's a random string of numbers, lowercase letters, and uppercase letters.
  • Session token: A token that's used to re-authenticate the player after the session expires. It's a randomly generated string. In the authentication responses, the field is called
    sessionToken
    .
  • Authentication Id Token: A JWT that contains a set of claims, including the PlayerId. It's passed into APIs for other Unity services to provide authorization. Other Unity Service's APIs need this token to authorize actions. In the API responses, the field is called
    idToken
    .

Login States

You're responsible for respecting when a player is logged in vs logged out.
  • A player is considered logged in when you have a valid id token for that player.
  • A player is considered logged out when you have an invalid id token for that player.
You're responsible for verifying that the id token is valid. For more information on how to verify the id token, refer to the Validating the idToken section. If the id token is expired and you want to keep the player logged in, then you must refresh the id token. Refer to the Refreshing the idToken section.

Use Cases

These tokens and the PlayerId allow Unity products and Unity games to capture player information during authentication. They enable:
  • A means to identify a player and store player game data (for example, saving game state and recording in-app purchases).
  • Consistent game experiences for the player (for example, points for leader boards and suggested in-app purchases).
  • Insight about the player's game behavior across multiple devices.
  • Multiplayer features on various platforms.
  • Digital Services Act notifications

Types of authentication

Anonymous authentication

Anonymous authentication is similar to a guest sign-in. It creates a new player for the game session without any input from the player. The player won't need to enter any sign-in credentials or to create a player profile. It's a quick way for a player to get started with your game.
Although this method has the lowest friction for players, anonymous authentication is not portable across devices since there is no way to re-authenticate the player from another device. Players aren't able to sign in to the same game with the same player profile from a different device unless they use platform-specific authentication.

Username Password Authentication

Username Password authentication allows players to create a username and password to sign in to your game. This method is portable across devices, so players can sign in to the same game with the same player account from a different device. This method also allows players to sign in to your game without using a third-party identity provider.

Code Linking

Code Linking enables a player to securely sign in to your game from one device to another using a temporary generated code. This method is portable across devices, so players can sign in to the same game with the same player account from a different device.

Custom ID

Custom ID allows developers to use their existing authentication systems to authentication their players with Unity Authentication. Developers can provision a service account and use that service account to exchange their own players ids for a Unity Authentication player id.

Platform-specific

Platform-specific authentication uses external identity providers. This means that you must create an identity provider configuration so that Unity Authentication can validate the player, making it possible to authenticate the same player from multiple devices.
The following Unity Gaming Services support Unity Authentication:
The following concerns products or services (each a "Third Party Product") that are not developed, owned, or operated by Unity. This information may not be up-to-date or complete, and is provided to you for your information and convenience only. Your access and use of any Third Party Product is governed solely by the terms and conditions of such Third Party Product. Unity makes no express or implied representations or warranties regarding such Third Party Products, and will not be responsible or liable, directly or indirectly, for any actual or alleged damage or loss arising from your use thereof (including damage or loss arising from any content, advertising, products or other materials on or available from the provider of any Third Party Products).
Documentation for the following external identity providers can be found in this section:
  • Apple
  • Apple Game Center
  • Google
  • Google Play Games
  • Facebook
  • Steam
  • Oculus
  • Custom OpenID Connect (OIDC)
Unity provides support for PC and mobile. Console support is available on an invite-only basis.

Set up the Unity Authentication service

When a new or returning user logs into your application, the Unity Authentication service uses the following to capture the user's information:
  • PlayerId
    : the main identifier for new and returning Unity Authentication end users.
  • sessionToken
    : a randomly-generated string that re-authenticates the user after the session expires.
  • idToken
    : a JSON Web Token (JWT) that contains a set of claims, including the
    PlayerId
    . The
    idToken
    provides authorization when passed into other Unity Services APIs.
The
PlayerId
,
sessionToken
, and
idToken
provide:
  • A way to identify a user and to store user data. For example, saving the game state and recording in-app purchases.
  • Consistent game experiences for the user. For example, points for leaderboards and suggested in-app purchases.
  • Insight about the user's game behavior across multiple devices.
  • Multiplayer features on different platforms.
The Unity Authentication service supports user authentication through anonymous or platform-specific authentication.

Set up anonymous authentication

Anonymous authentication is similar to a guest login. It allows the user to create a new user for the game session without entering login credentials or creating a profile.
Anonymous authentication isn't portable across devices because it's not possible to re-authenticate the anonymous user from another device.
To set up anonymous authentication, follow these steps:
  1. Find your Unity project ID in the Project Details section of your project in the Unity Dashboard.
  2. Call the following API to create an anonymous player ID:
curl -XPOST -H "ProjectId: <projectId>" https://player-auth.services.api.unity.com/v1/authentication/anonymous \-H 'Content-Type: application/json'
  1. Find the
    idToken
    and
    sessionToken
    fields in the JSON response object. The response will look similar to this:
{ "userId": "T7galGM3T1Bggbb3FfNrzMdivZOG", "idToken": "eyJhbGciOiJSUzI1NiIs...p_q74teH0MNTMQ", "sessionToken": "R5pKaP8kEUE2aG...pk08RGC7aM", "expiresIn": 3599, "user": { "id": "T7galGM3T1Bggbb3FfNrzMdivZOG", "disabled": false, "externalIds": [] }}
You can use the
idToken
as the user's authentication token when you call client APIs. To do so, include the
idToken
in the authorization header as the bearer token:
curl -H "Authorization: Bearer eyJhbGciOiJSUzI1NiIs...p_q74teH0MNTMQ" \https://services.api.unity.com/<ENDPOINT>

Set up Username Password authentication

Username Password Authentication allows players to create a username and password to sign in to your game. This method is portable across devices, so players can sign in to the same game with the same player profile from a different device. This method also allows players to sign in to your game without using a third-party identity provider.

Setup Steps

  1. In the Unity Dashboard, select Home > Projects.
  2. Select your project.
  3. Go to Development > Products.
  4. Select Player Authentication.
  5. Select Identity Providers.
  6. On the right side, select Add Identity Provider, and select Username Password.
  7. Select Add Identity Provider.
注意
Once you add the Username Password Identity Provider you will not be able to delete it. This is to protect user information from being lost in the event the Username Password Identity Provider is deleted. If you decide to no longer use this Identity Provider after enabling it, we recommend disabling the Identity Provider instead.

Sign Up

To sign a player up, call the API below:
curl --location --request POST 'https://player-auth.services.api.unity.com/v1/authentication/usernamepassword/sign-up' \--header 'Content-Type: application/json' \--header 'ProjectId: <projectId>' \--header 'Authorization: Bearer <Id Token from Unity Authentication>' \--data-raw '{ "username": "<username of the user>", "password": "<password of the user>"}'
Note that Authorization is an optional header. If the Authorization Header is not provided, then a new player is created. Otherwise, the API adds the username password to the existing player indicated by the ID token. The ID token can be retrieved from other authentication APIs, such as Anonymous sign-up, session token sign-in, external token auth, etc.

Username and Password restrictions

Below are the restrictions for both the username and password fields:

Username

  • The username must be between 3-20 characters long.
  • The username can only contain the following characters: a-z, 0-9, and the symbols [.][-][@][_].
  • The username is case-insensitive.

Password

  • The password must be between 8-30 characters long.
  • The password must contain at least one uppercase letter.
  • The password must contain at least one lowercase letter.
  • The password must contain at least one number.
  • The password must contain at least one symbol.

Sign In

To sign a player in, call the API below:
curl --location --request POST 'https://player-auth.services.api.unity.com/v1/authentication/usernamepassword/sign-in' \--header 'Content-Type: application/json' \--header 'ProjectId: <projectId>' \--data-raw '{ "username": "<username of the user>", "password": "<password of the user>"}'

Password update

To update the password of a user, call the API below:
curl --location --request POST 'https://player-auth.services.api.unity.com/v1/authentication/usernamepassword/update-password' \--header 'Content-Type: application/json' \--header 'ProjectId: <projectId>' \--header 'Authorization: Bearer <Id Token from Unity Authentication>' \--data-raw '{ "password": "<password of the user>", "newPassword": "<the password to be changed>"}'
Note that Authentication is a required header and must be specified in the request. This is because the user must be signed in to update their password. For the new password, the same restrictions apply as when signing up a user.

Set up Code Linking

Code Linking is a cross-platform authentication method that allows players to sign in across multiple devices by using a securely generated temporary code. This uses the Proof Key for Code Exchange (PKCE) protocol to ensure that only the client that generated the code can be authenticated from the code flow.

How Code Linking Works

  1. The game client requests a code from the unauthenticated device to which the user wants to sign in. A codeChallenge is provided in this Generate Sign In Code request.
  2. Once the request is made, a signInCode is sent back as a response.
  3. The player will then need to confirm the signInCode by entering it into the game client on the authenticated device.
  4. Next, the game client then calls the Code Confirmation API from an already authenticated device and include the signInCode within the request. This confirms that the unauthenticated device can be properly linked to the player's account.
  5. Lastly, the game client can now call the Sign in With Code API from the unauthenticated device, and include the codeVerifier within the request. The codeVerifier will be checked against the hashed codeChallenge, and if they match, the device will be signed in and authenticated.

Generating a codeChallenge and codeVerifier

The codeChallenge is a SHA-256 hashed value generated from a codeVerifier. The codeVerifier is a randomly generated base64 encoded string that is used to generate a codeChallenge. Both of these values must be between the lengths of 43-128 characters.
To generate a codeVerifier, use the following code:
package mainimport ( "crypto/rand" "encoding/base64" "fmt")func main() { b := make([]byte, 64) _, err := rand.Read(b) if err != nil { fmt.Println("error:", err) return } s := base64.RawURLEncoding.EncodeToString(b) fmt.Println(s)}
To generate a codeChallenge, use the following code:
package mainimport ( "crypto/sha256" "encoding/base64" "fmt")func main() { s := "codeVerifier" // Replace this with your base64 codeVerifier string b := sha256.Sum256([]byte(s)) encoded := base64.RawURLEncoding.EncodeToString(b[:]) fmt.Println(encoded)}
For more information on how these values are formatted, please check out: PKCE.

Code Linking Setup Steps

  1. In the Unity Dashboard, go to Development > Products.
  2. Select Player Authentication.
  3. Select Identity Providers.
  4. Select Add Identity Provider > Code Linking.
  5. Select Add provider.

Generate Sign In Code

This API requests a code to be generated for an unauthenticated device. The player will need to confirm the sign in request on an already authenticated device in order to sign in to the new device. To generate a sign-in code, call the API below:
curl --location --request POST 'https://player-auth.services.api.unity.com/v1/authentication/code-link/generate' \--header 'Content-Type: application/json' \--header 'ProjectId: <projectId>' \--data-raw '{ "codeChallenge": "<string>", "identifier": "<string>"}'
Field information:
  • codeChallenge: The code challenge that will be used to validate the code verifier sent in subsequent Sign In with Code requests, ensuring that those requests originated from the same device that generated the sign-in code.
  • identifier: An optional identifier that can be used to identify the device or to provide a hint for the unauthenticated device.
The response will contain several values:
  • codeLinkSessionId: A unique identifier for the code-linking session.
  • signInCode: The code used as input in an authorized device.
  • expiration: The timestamp of when the signInCode will expire.

Sign In with Code

This API signs a player in using a codeLinkSessionId and a codeVerifier to identify the original request. A codeLinkSessionId is passed as a parameter, and is used to specify the code-linking session associated with the initial unauthenticated device.
curl --location --request POST 'https://player-auth.services.api.unity.com/v1/authentication/code-link/sign-in/<codeLinkSessionId>' \--header 'Content-Type: application/json' \--header 'ProjectId: <projectId>' \--data-raw '{ "codeVerifier": "<string>"}'
Field information:
  • codeVerifier: Validates the original request came from the same device.
  • sessionToken: The session token of the authenticated user.
注意
On consoles, to complete a code-link sign in request you need to link the user received in the Sign In With Code with the console's user by linking the idToken received to the console account using the Link APIs.

Get Code Information (Optional)

This optional API can be used by an authenticated client to get information about the sign in code or to verify you are attempting to code link to the correct unauthenticated device. To call this API, no authentication is required.
curl --location --request POST 'https://player-auth.services.api.unity.com/v1/authentication/code-link/info' \--header 'Content-Type: application/json' \--header 'ProjectId: <projectId>' \--data-raw '{ "signInCode": "<string>"}'
Field information:
  • signInCode: The code that is required to get information from an authorized device.
The response will contain an identifier, which can be used to identify the device that requested the code.
{ "identifier": "<string>", // Identifies the device for extra confirmation (Optional)}

Code Confirmation

This API is used by an authenticated client to confirm code linking for an unauthenticated device. This verifies that the device that requested the code is the same device that is attempting to sign in.
curl --location --request POST 'https://player-auth.services.api.unity.com/v1/authentication/code-link/confirm' \--header 'Content-Type: application/json' \--header 'ProjectId: <projectId>' \--header 'Authorization: Bearer <Id Token from Unity Authentication>' \--data-raw '{ "signInCode": "<string>", "sessionToken": "<string>"}'
Field information:
  • signInCode: The code that is required to get information from an authorized device.
  • sessionToken: The session token of the authenticated user.
注意
Code confirmation also supports consoles by replacing the sessionToken parameter with the console's idProvider and player's externalToken.

Digital Services Act Notifications

To comply with the Digital Services Act, which takes full effect on February 17, 2024, you must integrate with the new Notifications APIs. Refer to our DSA compliance efforts page for more information.
This article explains how to integrate with the Notification APIs to:
  • Check for new notifications for a signed in player.
  • Check for new notifications for a restricted player.

Notifications for signed in player

Every time a player successfully signs in, the Authentication SDK validates if there are any notifications available for that player and populates the
lastNotificationDate
field in the
AuthenticationResponse
, with the date the last notification was created, in milliseconds, since Unix epoch. You must:
  1. Confirm the
    lastNotificationDate
    field is not null after every successful sign in, meaning there are notifications available for that player.
  2. Confirm if the
    lastNotificationDate
    is greater than the value you stored for the last notification the player read.
  3. Retrieve the player's notifications by calling the ReadNotifications API.
curl --location 'https://player-auth.services.api.unity.com/v1/users/<playerId>/notifications' \--header 'projectId: <projectId>' \--header 'Authorization: Bearer <Id Token from Unity Authentication>'
{ "notifications": [ { "id": "<string>", // Notification ID "type": "<string>", // DSA "playerID": "<string>", "caseID": "<string>", "projectID": "<string>", "message": "<string>", // Message details that should be displayed to the player "createdAt": "<int>" // Unix epoch timestamp } ]}
  1. Display the notifications to the player.
  2. When the player reads a notification you must store the greater value between that notification's
    createdAt
    value and the stored value for the player's last read notification.

Notifications for a restricted player

When a player tries to sign in and fails due to them being restricted, an
AuthenticationError
response is returned and it contains a new
notifications
field in the
details
, which contains all notifications available to that player, or null if none are available. You must:
  1. Parse the
    AuthenticationError
    response, after every failed sign in attempt.
{ "status":403, "title":"BANNED_USER", "detail":"The user is banned until 2025-01-01 00:00:00 +0000 UTC", "details":[ { "notifications": [ { "id": "<string>", // Notification ID "type": "<string>", // DSA "playerID": "<string>", "caseID": "<string>", "projectID": "<string>", "message": "<string>", // Message details that should be displayed to the player "createdAt": "<int>" // Unix epoch timestamp } ] } ]}
  1. Confirm if the
    notifications
    field in the details isn't null.
  2. Display the notifications to the player.

Custom ID authentication

Custom ID authentication allows the player to authenticate with your existing authentication game server and use the game server's player id with a service account to exchange for a Unity player id.
The following steps will guide you to set up your game with the ability for players to sign in to your game using your existing authentication system and get an access token.

Setup

  1. In the Unity Dashboard, go to Development > Products.
  2. Select Player Authentication.
  3. Select Identity Providers.
  4. On the right side, select Add Identity Provider, and select Custom ID.
  5. Select Add provider.

Set up Service Account

To use the Custom ID authentication you need to Create a Service Account to authenticate your game server with Unity Authentication. You also need to add the project role Player Authentication Token Issuer to the Service Account, to authorize the game server to perform the Custom ID authentication.

Find your Unity Project ID

  1. In the Unity Dashboard, select Home > Projects.
  2. Open the project that you want to use to call Client APIs.
  3. Find the Project Id in the Project Details.

Authenticate with Custom ID

To perform the Custom ID authentication follow these steps:
  1. Authenticate the player on your game server.
  2. Call the Token Exchange API to retrieve a stateless token if not expired
curl -X POST -H "Authorization: Basic <SERVICE_ACCOUNT_KEY_ID>:<SECRET_KEY>" \https://services.api.unity.com/auth/v1/token-exchange?projectId=<PROJECT_ID>&environmentId=<ENVIRONMENT_ID>
注意
You should store the stateless token locally and refresh it when it expires instead of retrieving a new token on every call to avoid hitting the rate limit threshold.
  1. Exchange the game server's player id for a Unity player id
curl -X POST -H 'Content-Type: application/json' \-H 'Authorization: Bearer <STATELESS_TOKEN>' \-d '{ "externalId": "<GAME_SERVER_PLAYER_ID>", "signInOnly": false}' \https://player-auth.services.api.unity.com/v1/projects/<PROJECT_ID>/authentication/server/custom-id
The API will respond with a JSON object. Find the
idToken
and
sessionToken
fields in the JSON object. The response will look like:
{ "userId": "T7galGM3T1Bggbb3FfNrzMdivZOG", "idToken": "eyJhbGciOiJSUzI1NiIs...p_q74teH0MNTMQ", "sessionToken": "R5pKaP8kEUE2aG...pk08RGC7aM", "expiresIn": 3599, "user": { "id": "T7galGM3T1Bggbb3FfNrzMdivZOG", "disabled": false, "externalIds": [ { "providerId": "custom", "externalId": "<GAME_SERVER_ID>" } ] }}
The
idToken
can then be used to call Client APIs as the player's Authentication token when needed. The token should be placed in the Authorization header as a Bearer token. For example:
curl -H "Authorization: Bearer eyJhbGciOiJSUzI1NiIs...p_q74teH0MNTMQ" \https://services.api.unity.com/<ENDPOINT>
To link an existing Unity Authentication account with a Custom ID from your own authentication service you can follow these steps:
  1. Authenticate the player with UAS using any other sign-in method.
  2. When authenticating the player with your Authentication system, send the
    idToken
    from the authentication response.
  3. Follow the steps in Authenticate with Custom ID, but in step three include the
    idToken
    in the payload as the
    accessToken
    field:
curl -X POST -H 'Content-Type: application/json' \-H 'Authorization: Bearer <STATELESS_TOKEN>' \-d '{ "externalId": "<GAME_SERVER_PLAYER_ID>", "signInOnly": false, "accessToken": "<idToken>"}' \https://player-auth.services.api.unity.com/v1/projects/<PROJECT_ID>/authentication/server/custom-id
UAS returns an error if:
  • The Custom ID is already linked to another UAS account.
  • The UAS account that generated the
    accessToken
    is linked to another Custom ID.
  • The
    accessToken
    is invalid.

Platform-Specific Authentication

Set up platform-specific authentication

Platform-specific authentication uses external identity providers to authenticate users. It provides the user with a consistent login method and allows them to access their account from different devices.
注意
The following concerns a product or service (each a "Third Party Product") that is not developed, owned, or operated by Unity. This information may not be up-to-date or complete, and is provided to you for your information and convenience only. Your access and use of any Third Party Product is governed solely by the terms and conditions of such Third Party Product. Unity makes no express or implied representations or warranties regarding such Third Party Products, and will not be responsible or liable, directly or indirectly, for any actual or alleged damage or loss arising from your use thereof (including damage or loss arising from any content, advertising, products or other materials on or available from the provider of any Third Party Products).
You can set up the following identity providers for platform-specific authentication:
You can set up an identity provider through:
  • The Editor settings in the Unity Editor, if you have the Unity Authentication SDK. For more information on setting up an identity provider with the Unity Editor, refer to Set up external identity providers.
  • The Unity Dashboard.

Apple

To set up the Apple identity provider, follow these steps:
  1. Register and configure an application with Apple and find your Apple Client ID.
  2. In the Unity Dashboard, go to Development > Products.
  3. Select Player Authentication.
  4. Select Identity Providers.
  5. Select Add Identity Provider > Sign in with Apple.
  6. Enter your App ID and enable the Enable Identity Provider checkbox.
  7. Select Add provider.

Apple Game Center

To set up the Apple Game Center identity provider, follow these steps:
  1. Register and configure an application with the Apple Game Center and find your Bundle ID.
  2. In the Unity Dashboard, go to Development > Products.
  3. Select Player Authentication.
  4. Select Identity Providers.
  5. Select Add Identity Provider > Apple Game Center.
  6. Enter your Bundle ID and enable the Enable Identity Provider checkbox.
  7. Select Add provider.

Facebook

To set up the Facebook identity provider, follow these steps:
  1. Register and configure an application as a Meta developer and find your App ID and App Secret.
  2. In the Unity Dashboard, go to Development > Products.
  3. Select Player Authentication.
  4. Select Identity Providers.
  5. Select Add Identity Provider > Facebook.
  6. Enter your Ap ID and Secret ID, and enable the Enable Identity Provider checkbox.
  7. Select Add provider.
Unity supports the following:

Google

To set up the Google identity provider, follow these steps:
  1. Register and configure an application with Google and find your Client ID.
  2. In the Unity Dashboard, go to Development > Products.
  3. Select Player Authentication.
  4. Select Identity Providers.
  5. Select Add Identity Provider > Sign in with Google.
  6. Enter your Client ID and enable the Enable Identity Provider checkbox.
  7. Select Add provider.

Google Play Games

To set up the Google Play Games identity provider, follow these steps:
  1. Register and configure an application with Google Play Games and find your Client ID and Client Secret.
  2. In the Unity Dashboard, go to Development > Products.
  3. Select Player Authentication.
  4. Select Identity Providers.
  5. Select Add Identity Provider > Google Play Games.
  6. Enter your Client ID and Client Secret, and enable the Enable Identity Provider checkbox.
  7. Select Add provider.

Oculus

To set up the Oculus identity provider, follow these steps:
  1. Register and configure an application with Oculus and find your App ID and App Secret.
  2. In the Unity Dashboard, go to Development > Products.
  3. Select Player Authentication.
  4. Select Identity Providers.
  5. Select Add Identity Provider > Oculus.
  6. Enter your App ID and Secret ID, and enable the Enable Identity Provider checkbox.
  7. Select Add provider.

Custom OpenID Connect (OIDC)

To set up the OIDC identity provider, follow these steps:
  1. Register and configure an application with the OIDC provider and find your Client ID and Issuer URL.
  2. In the Unity Dashboard, go to Development > Products.
  3. Select Player Authentication.
  4. Select Identity Providers.
  5. Select Add Identity Provider > OpenID Connect.
  6. Enter a name for your OIDC provider, your Client ID, and your Issuer URL.
  • The name for your OIDC provider:
  • Must start with
    oidc-
    .
  • Must have a maximum length of 20 characters, including the
    oidc-
    prefix.
  • Can contain
    a-z
    lowercase characters,
    0-9
    number characters, or the
    .
    ,
    -
    ,
    _
    characters.
  • Your Issuer URL:
  • Must be in the
    https
    protocol scheme.
  • Must have a maximum length of 100 characters.
  • Can't have an
    openid-configuration
    response larger than 20000 bytes.
  • Can't have a
    jwks
    response larger than 20000 bytes.
  1. Enable the Enable Identity Provider checkbox.
  2. Select Add provider.

Steam

To set up the Steam identity provider, follow these steps:
  1. Register and configure an application with Steam and find your App ID and Key.
  2. In the Unity Dashboard, go to Development > Products.
  3. Select Player Authentication.
  4. Select Identity Providers.
  5. Select Add Identity Provider > Steam.
  6. Enter your App ID and Key, and enable the Enable Identity Provider checkbox.
  7. Select Add provider.
To set up Multiple App Ids (e.g.: Play Test, Demo, Alpha, etc), follow these steps:
  1. In the Unity Dashboard, go to Development > Products.
  2. Select Player Authentication.
  3. Select Identity Providers.
  4. Click the Steam provider already set up for your project to Edit.
  5. Click the Add button to the right of Additional App ID.
  6. Input the App ID and a Description.
  7. Click Save.
注意
The player will have the same Unity Authentication Player ID for all App IDs under the same project, so use your best judgement to set up different environments to keep the player data (Economy, Cloud Save, etc) scoped to each App ID and avoid production data mixing with non-production data.

Platform-specific authentication APIs

When a user logs into the identity provider, you gain access to their access token. You can pass their access token into one of the following APIs:
  • External token API
  • Link API
  • Unlink API
Unity only supports the ID Token as a token input for OIDC. For more information on the ID token, refer to the OIDC documentation.
These APIs require a project ID and an ID provider as inputs. To find your project ID, go to the Project Details section of your project in the Unity Dashboard. The project ID is sent as a header and the identity provider is sent as part of the API path.
Use the following constant values as inputs when you call platform-specific authentication APIs:
  • For Apple:
    apple.com
  • For Apple Game Center:
    apple-game-center
  • For Facebook:
    facebook.com
  • For Google:
    google.com
  • For Google Play Games:
    google-play-games
  • For Oculus:
    oculus
  • For OIDC: the name you configured for your OIDC provider
  • For Steam:
    steampowered.com

Token Example

"token": "<Access or Id token from Third Party>"

External token API

The external token API creates or logs in a Unity Authentication account with a platform-specific identity. Use the external token API when:
  • The user isn't logged into Unity Authentication
  • The user is logged into the identity provider
  • You want the user to log in with their identity provider access token
After you call the external token API, the Unity Authentication service creates a new user and links them to the external identity you specified on the access token.
You don't need to call the external token API again after you have successfully called it once.

External Token Example

"token": "<Access or Id token from Third Party>"
JSON object response example:
{ "userId": "Z1bNra4q4LSnyl3P9HM2ohb6Ub3f", "idToken": "eyJhbG...Tj0ew", "sessionToken": "YgYyi...KbrU", "expiresIn": 3599, "user": { "id": "Z1bNra4q4LSnyl3P9HM2ohb6Ub3f", "disabled": false, "externalIds": [ { "providerId": "<Id Provider>", "externalId": "<Player's External Id>" } ] }}

Oculus API input

To log in with the Oculus identity provider, you must include the user ID and the nonce as inputs in the API request body.
{ "token": "<Nonce from Oculus>", "oculusConfig": { "userId": "<player Id from Oculus>" }}
For more information, refer to the Oculus documentation.

Steam API optional input

The Steam Identity provider has an optional configuration object, steamConfig for:
  • Increased security by including the identity field, which MUST be the same as then one used when requesting the steam ticket.
  • Multiple App Id support by including the appId used to request the steam ticket. Note: This needs to have been previously configured in the dashboard
{ "token": "<Ticket token>", "steamConfig": { "identity": "<string>", "appId": "<string>" }}

Apple Game Center API input

To log in with the Apple Game Center identity provider, you must include the following values:
  • Signature, which is contained inside the
    token
    field
  • Team player ID
  • Salt
  • Timestamp
  • Public key URL
The signature and salt values in your API request body must be Base64 encoded string values of the raw value you got from Apple. The timestamp input is only valid for 10 minutes.
{ "token": "<Signature from Apple Game Center>", "appleGameCenterConfig": { "teamPlayerId": "<Team Player Id from Apple Game Center>", "salt": "<Salt from Apple Game Center>", "timestamp": "<Timestamp from Apple Game Center>", "publicKeyUrl": "<Public Key Url from Apple Game Center>" }}
Before you call the external token API, make sure to call Apple's FetchItems API to receive fresh inputs. For more information on Apple's API, refer to the Apple Game Center documentation.

Prevent the creation of a new user

By default, the external token API creates a new user on the Unity Authentication service if a user doesn't already exist. To prevent the creation of a new Unity Authentication user, set the
signInOnly
flag to
true
.
If the user doesn't exist, the API request fails and doesn't create a new user.
curl --location --request POST 'https://player-auth.services.api.unity.com/v1/authentication/external-token/<Id Provider>' \--header 'Content-Type: application/json' \--header 'ProjectId: <projectId>' \--data-raw '{ "token": "<Access or Id token from Third Party>", "signInOnly": true}'
The link API links a Unity Authentication account with a platform-specific identity. Use the link API when:
  • The user is logged into Unity Authentication
  • The user is logged into the identity provider
  • You want to link the Unity Authentication user to the external identity
The user's Unity Authentication ID token is used to authorize actions on their account. Make sure to save the user's ID token from a previous authentication response.
After you call the link API, the user becomes linked to the external identity.
Link API call example:
"token": "<Access or Id token from Third Party>"
JSON object response example:
{ "userId": "WIIXBaxb5g1Y5ZPwbZErapmbOcTl", "idToken": "", "sessionToken": "", "expiresIn": 0, "user": { "id": "WIIXBaxb5g1Y5ZPwbZErapmbOcTl", "disabled": false, "externalIds": [ { "providerId": "<Id Provider>", "externalId": "<External Id>" } ] }}
You can only link a single Unity Authentication user to an external identity. Your link API request fails if another user is already linked to the identity.
To disconnect the external identity from the already-linked user and link it to a different user instead, set the
forceLink
flag to
true
.
"token": "<Access or Id token from Third Party>", "forceLink": true
注意
If the link API call fails, the external identity can be unlinked from both Unity Authentication users. If this happens, call the API again.
The unlink API unlinks a Unity Authentication account from a platform-specific identity. Use the unlink API when:
  • The user is logged into Unity Authentication
  • You want to unlink the Unity Authentication user from the external identity
To unlink a user, you must have their external ID. You can find the external ID in the
externalIds
field of the external token or link API responses.
The user's Unity Authentication ID token is used to authorize actions on their account. Make sure to save the user's ID token from a previous authentication response.
After you call the unlink API, the user becomes unlinked from the external identity.
Unlink API call example:
"externalId": "<Third Party External Id>"
JSON object response example:
{ "userId": "WIIXBaxb5g1Y5ZPwbZErapmbOcTl", "idToken": "", "sessionToken": "", "expiresIn": 0, "user": { "id": "WIIXBaxb5g1Y5ZPwbZErapmbOcTl", "disabled": false, "externalIds": [] }}

Get player API

The get player API checks information about the user. Use the get player API when:
  • The user is logged into Unity Authentication
  • You need information about the user

Get Player API Example

Get player API call example:
curl --location --request GET 'https://player-auth.services.api.unity.com/v1/users/<playerId>' \--header 'Content-Type: application/json' \--header 'ProjectId: <projectId>' \--header 'Authorization: Bearer <Id Token from Unity Authentication>'
JSON object response example:
{ "id": "Tg1m3aq3nVEb9o9kG4vNeqcixLH8", "disabled": false, "externalIds": [], "createdAt": "302899439", "lastLoginAt": "302899439", "username": "Current_User_57"}

Delete player API

The delete player API deletes the user. Use the delete player API when:
  • The user is logged into Unity Authentication
  • You need to delete the user
注意
You cannot restore a user after they have been deleted.

Delete player API Example

Delete player API call example:
curl --location --request DELETE 'https://player-auth.services.api.unity.com/v1/users/<playerId>' \--header 'Content-Type: application/json' \--header 'ProjectId: <projectId>' \--header 'Authorization: Bearer <Id Token from Unity Authentication>'
JSON object response example:
{}
The response is an empty object because the user information has been deleted.

Non-platform-specific authentication APIs

Validate the token ID

To check the login status of a user, you must verify the status of their token ID. Logged in users have a valid token ID, while logged out users have an invalid token ID.
The
idToken
is a JWT that can be verified. For more information about JWTs, refer to the RFC 7519 JWT overview.
If you have retrieved the user's
idToken
directly from the
https://player-auth.services.api.unity.com
endpoint, you can skip steps 1 and 2. If you have retrieved the user's
idToken
from a different endpoint, follow steps 1 and 2 to make sure the
idToken
hasn't been modified.
To validate the
idToken
, follow these steps:
  1. Fetch the JSON Web Key Set (JWKS) from Unity Authentication. The JWKS has the public key used to validate tokens.
  2. Verify the signature of the
    tokenId
    to make sure that the token is signed by the Unity Authentication server and that the token's claims haven't been modified.
  3. Decode the base64url-encoded
    tokenId
    .
  4. Verify that the claims are valid.

Fetch the JWKS

To fetch the JWKS, access the following endpoint:
https://player-auth.services.api.unity.com/.well-known/jwks.json
The response is a standard JWKS.
{ "keys": [ { "use": "sig", "kty": "RSA", "kid": "public:f66a7494-5315-4ca4-8150-e846573ffc1d", "alg": "RS256", "n": "...", "e": "AQAB" }, { "use": "sig", "kty": "RSA", "kid": "public:c2f38f4a-a115-40a4-a530-10d08211b6ac", "alg": "RS256", "n": "...", "e": "AQAB" } ]}
For better results, refresh your JWKS every 8 hours. If you can't find the
idToken
in the cached JWKS, fetch the JWKS again. Make sure not to refresh the JWKS too frequently or a rate limit will be enforced. For more information on the rate limit, refer to the Rate limits page.

Verify claims

To make sure that your token is valid, verify the token's following claims:
  • exp
    : expiration. The epoch timestamp when the token expires.
  • nbf
    : not before. The epoch timestamp when the token becomes valid.
  • (Optional)
    sub
    : the Unity Authentication user ID.
  • (Optional)
    project_id
    : the Unity project ID.
  • (Optional)
    jti
    : the unique token ID.
  • (Optional)
    iss
    : the Issuer URL. The expected claim value is
    https://player-auth.services.api.unity.com
    .

Refresh the token ID

If a user's token ID is expired and you want to keep them logged in, you must refresh their token. The token expires in 1 hour. Use the
sessionToken
from your original authentication response on the
/authentication/anonymous
or
/authentication/external
endpoints to receive an updated
idToken
.
curl -XPOST -H "ProjectId: <projectId>" https://player-auth.services.api.unity.com/v1/authentication/session-token \-H 'Content-Type: application/json' \-d '{"sessionToken": "R5pKaP8kEUE2aG...pk08RGC7aM"}'
JSON object response example:
{ "userId": "T7galGM3T1Bggbb3FfNrzMdivZOG", "idToken": "eyJhbGciOiJSUzI1NiIsImt...Lc_RN4mn9Hq2k3tFOX5wukCganFjA", "sessionToken": "t1X_x7luG7uVvfTQKp6fd2f...MV6dSZWaJOHNymkmQ-es6qOkHF8", "expiresIn": 3599, "user": { "id": "T7galGM3T1Bggbb3FfNrzMdivZOG", "disabled": false, "externalIds": [] }}
The response includes a different
sessionToken
that you can use to refresh the token again. Make sure to always use the latest
sessionToken
returned by the API.

Authorize the user for a specific environment

By default, Unity Authentication authorizes users to access resources in the default production environment. To authorize a user for a different environment, you must add the header
UnityEnvironment
to your
idToken
request.
The
idToken
request can include
/anonymous
,
/external-token
, or
/session-token
. The value of the header is the environment name. You can check the available environments in a project in UDash.
curl -XPOST -H "ProjectId: <projectId>" -H "UnityEnvironment: <environment name>" https://player-auth.services.api.unity.com/v1/authentication/anonymous

Error codes

This section describes errors you might receive when making API calls to the Unity Authentication service.
When you receive an error, the response includes the following:
  • status
    : The HTTP status code.
  • title
    : A custom error code defined by the authentication service.
  • detail
    : A message providing more details about the error returned.
If the error code status is in the 400-499 range, the error might be related to the API inputs and coming from the client side.

General errors

You might receive the following errors when making API calls to the Unity Authentication service:

Status

Title

Detail

Troubleshooting

404
RESOURCE_NOT_FOUND
N/AMake sure that the
projectId
header input is correct and that the local project is properly linked to the Unity Organization and Project.
400
INVALID_PARAMETERS
Invalid environment name provided
Make sure that you're calling a valid, existing environment. For more information on environments, refer to the environment documentation.

Sign in and account linking errors with external identity providers

You might receive the following errors when using the
/link
and
/external-token
APIs:

Detail

Description

Troubleshooting

Token is expired
,
Not valid yet
, or
Token issued at claim is in the future
Indicates that the token is invalid.Refresh the external token, then sign in and link the token again.
Invalid audience
Indicates that the application or client ID you have registered with the Unity Authentication service doesn't match the application ID listed in the audience field of your token.Verify that the application or client ID is in the correct format and matches the ID from your identity provider.
Invalid issuer
or
Invalid signature
Indicates that the ID token wasn't issued by the expected source.Verify where the ID token was fetched from and that the Unity Authentication service supports the source.
Malformed token
,
Validation failed
, or
Invalid token
Indicates there's an issue with the token input.Verify that the token type is expected for the identity provider, the token hasn't been manipulated after being fetched, and get a new token.