Client authentication
Learn how to authenticate client APIs using Unity Authentication, including anonymous, username-password, code linking, custom ID, and platform-specific authentication.
読み終わるまでの所要時間 25 分最終更新 2ヶ月前
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.
Unity Authentication is currently supported for the following Unity Gaming Services:
- Cloud Save
- Economy
- Cloud Code
- Leaderboards
- Lobby
- Friends
- Player Names
- Remote Config
- Distributed Authority
- Relay Allocations
- Multiplay Game Server Lifecycle
- Safe Voice Client
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.
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:- Cloud Save
- Economy
- Cloud Code
- Leaderboards
- Lobby
- Friends
- Player Names
- Remote Config
- Distributed Authority
- Relay Allocations
- Multiplay Game Server Lifecycle
- Safe Voice Client
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:- : the main identifier for new and returning Unity Authentication end users.
PlayerId - : a randomly-generated string that re-authenticates the user after the session expires.
sessionToken - : a JSON Web Token (JWT) that contains a set of claims, including the
idToken. ThePlayerIdprovides authorization when passed into other Unity Services APIs.idToken
PlayerIdsessionTokenidToken- 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.
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.
To set up anonymous authentication, follow these steps:
- Find your Unity project ID in the Project Details section of your project in the Unity Dashboard.
- 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'
- Find the and
idTokenfields in the JSON response object. The response will look similar to this:sessionToken
You can use the{ "userId": "T7galGM3T1Bggbb3FfNrzMdivZOG", "idToken": "eyJhbGciOiJSUzI1NiIs...p_q74teH0MNTMQ", "sessionToken": "R5pKaP8kEUE2aG...pk08RGC7aM", "expiresIn": 3599, "user": { "id": "T7galGM3T1Bggbb3FfNrzMdivZOG", "disabled": false, "externalIds": [] }}
idTokenidTokencurl -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
- In the Unity Dashboard, select Home > Projects.
- Select your project.
- Go to Development > Products.
- Select Player Authentication.
- Select Identity Providers.
- On the right side, select Add Identity Provider, and select Username Password.
- Select Add Identity Provider.
Sign Up
To sign a player up, call the API below: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.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>"}'
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: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.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>"}'
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
- 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.
- Once the request is made, a signInCode is sent back as a response.
- The player will then need to confirm the signInCode by entering it into the game client on the authenticated device.
- 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.
- 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:To generate a codeChallenge, 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)}
For more information on how these values are formatted, please check out: PKCE.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)}
Code Linking Setup Steps
- In the Unity Dashboard, go to Development > Products.
- Select Player Authentication.
- Select Identity Providers.
- Select Add Identity Provider > Code Linking.
- 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:Field information: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>"}'
- 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.
- 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.Field information: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>"}'
- codeVerifier: Validates the original request came from the same device.
- sessionToken: The session token of the authenticated user.
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.Field information: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>"}'
- signInCode: The code that is required to get information from an authorized device.
{ "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.Field information: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>"}'
- signInCode: The code that is required to get information from an authorized device.
- sessionToken: The session token of the authenticated user.
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 thelastNotificationDateAuthenticationResponse- Confirm the field is not null after every successful sign in, meaning there are notifications available for that player.
lastNotificationDate - Confirm if the is greater than the value you stored for the last notification the player read.
lastNotificationDate - 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 } ]}
- Display the notifications to the player.
- When the player reads a notification you must store the greater value between that notification's value and the stored value for the player's last read notification.
createdAt
Notifications for a restricted player
When a player tries to sign in and fails due to them being restricted, anAuthenticationErrornotificationsdetails- Parse the response, after every failed sign in attempt.
AuthenticationError
{ "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 } ] } ]}
- Confirm if the field in the details isn't null.
notifications - 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
- In the Unity Dashboard, go to Development > Products.
- Select Player Authentication.
- Select Identity Providers.
- On the right side, select Add Identity Provider, and select Custom ID.
- 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
- In the Unity Dashboard, select Home > Projects.
- Open the project that you want to use to call Client APIs.
- Find the Project Id in the Project Details.
Authenticate with Custom ID
To perform the Custom ID authentication follow these steps:- Authenticate the player on your game server.
- 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>
- Exchange the game server's player id for a Unity player id
The API will respond with a JSON object. Find thecurl -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
idTokensessionTokenThe{ "userId": "T7galGM3T1Bggbb3FfNrzMdivZOG", "idToken": "eyJhbGciOiJSUzI1NiIs...p_q74teH0MNTMQ", "sessionToken": "R5pKaP8kEUE2aG...pk08RGC7aM", "expiresIn": 3599, "user": { "id": "T7galGM3T1Bggbb3FfNrzMdivZOG", "disabled": false, "externalIds": [ { "providerId": "custom", "externalId": "<GAME_SERVER_ID>" } ] }}
idTokencurl -H "Authorization: Bearer eyJhbGciOiJSUzI1NiIs...p_q74teH0MNTMQ" \https://services.api.unity.com/<ENDPOINT>
Link with Custom ID
To link an existing Unity Authentication account with a Custom ID from your own authentication service you can follow these steps:- Authenticate the player with UAS using any other sign-in method.
-
When authenticating the player with your Authentication system, send the from the authentication response.
idToken -
Follow the steps in Authenticate with Custom ID, but in step three include the in the payload as the
idTokenfield:accessToken
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
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.
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:- Register and configure an application with Apple and find your Apple Client ID.
- In the Unity Dashboard, go to Development > Products.
- Select Player Authentication.
- Select Identity Providers.
- Select Add Identity Provider > Sign in with Apple.
- Enter your App ID and enable the Enable Identity Provider checkbox.
- Select Add provider.
Apple Game Center
To set up the Apple Game Center identity provider, follow these steps:- Register and configure an application with the Apple Game Center and find your Bundle ID.
- In the Unity Dashboard, go to Development > Products.
- Select Player Authentication.
- Select Identity Providers.
- Select Add Identity Provider > Apple Game Center.
- Enter your Bundle ID and enable the Enable Identity Provider checkbox.
- Select Add provider.
- Register and configure an application as a Meta developer and find your App ID and App Secret.
- In the Unity Dashboard, go to Development > Products.
- Select Player Authentication.
- Select Identity Providers.
- Select Add Identity Provider > Facebook.
- Enter your Ap ID and Secret ID, and enable the Enable Identity Provider checkbox.
- Select Add provider.
- Register and configure an application with Google and find your Client ID.
- In the Unity Dashboard, go to Development > Products.
- Select Player Authentication.
- Select Identity Providers.
- Select Add Identity Provider > Sign in with Google.
- Enter your Client ID and enable the Enable Identity Provider checkbox.
- Select Add provider.
Google Play Games
To set up the Google Play Games identity provider, follow these steps:- Register and configure an application with Google Play Games and find your Client ID and Client Secret.
- In the Unity Dashboard, go to Development > Products.
- Select Player Authentication.
- Select Identity Providers.
- Select Add Identity Provider > Google Play Games.
- Enter your Client ID and Client Secret, and enable the Enable Identity Provider checkbox.
- Select Add provider.
Oculus
To set up the Oculus identity provider, follow these steps:- Register and configure an application with Oculus and find your App ID and App Secret.
- In the Unity Dashboard, go to Development > Products.
- Select Player Authentication.
- Select Identity Providers.
- Select Add Identity Provider > Oculus.
- Enter your App ID and Secret ID, and enable the Enable Identity Provider checkbox.
- Select Add provider.
Custom OpenID Connect (OIDC)
To set up the OIDC identity provider, follow these steps:- Register and configure an application with the OIDC provider and find your Client ID and Issuer URL.
- In the Unity Dashboard, go to Development > Products.
- Select Player Authentication.
- Select Identity Providers.
- Select Add Identity Provider > OpenID Connect.
- 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 prefix.
oidc- - Can contain lowercase characters,
a-znumber characters, or the0-9,.,-characters._ - Your Issuer URL:
- Must be in the protocol scheme.
https - Must have a maximum length of 100 characters.
- Can't have an response larger than 20000 bytes.
openid-configuration - Can't have a response larger than 20000 bytes.
jwks
- Enable the Enable Identity Provider checkbox.
- Select Add provider.
Steam
To set up the Steam identity provider, follow these steps:- Register and configure an application with Steam and find your App ID and Key.
- In the Unity Dashboard, go to Development > Products.
- Select Player Authentication.
- Select Identity Providers.
- Select Add Identity Provider > Steam.
- Enter your App ID and Key, and enable the Enable Identity Provider checkbox.
- Select Add provider.
- In the Unity Dashboard, go to Development > Products.
- Select Player Authentication.
- Select Identity Providers.
- Click the Steam provider already set up for your project to Edit.
- Click the Add button to the right of Additional App ID.
- Input the App ID and a Description.
- Click Save.
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
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
External Token Example
JSON object response example:"token": "<Access or Id token from Third Party>"
{ "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.For more information, refer to the Oculus documentation.{ "token": "<Nonce from Oculus>", "oculusConfig": { "userId": "<player Id from Oculus>" }}
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 field
token - Team player ID
- Salt
- Timestamp
- Public key URL
{ "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>" }}
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 thesignInOnlytruecurl --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}'
Link API
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
Link API Example
Link API call example:JSON object response example:"token": "<Access or Id token from Third Party>"
{ "userId": "WIIXBaxb5g1Y5ZPwbZErapmbOcTl", "idToken": "", "sessionToken": "", "expiresIn": 0, "user": { "id": "WIIXBaxb5g1Y5ZPwbZErapmbOcTl", "disabled": false, "externalIds": [ { "providerId": "<Id Provider>", "externalId": "<External Id>" } ] }}
Force link a user to an external identity
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 theforceLinktrue"token": "<Access or Id token from Third Party>", "forceLink": true
Unlink API
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
externalIdsUnlink API Example
Unlink API call example:JSON object response example:"externalId": "<Third Party External Id>"
{ "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:JSON object response 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>'
{ "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
Delete player API Example
Delete player API call example:JSON object response 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>'
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. TheidToken
To validate the
idToken- Fetch the JSON Web Key Set (JWKS) from Unity Authentication. The JWKS has the public key used to validate tokens.
- Verify the signature of the to make sure that the token is signed by the Unity Authentication server and that the token's claims haven't been modified.
tokenId - Decode the base64url-encoded .
tokenId - Verify that the claims are valid.
Fetch the JWKS
To fetch the JWKS, access the following endpoint:The response is a standard JWKS.https://player-auth.services.api.unity.com/.well-known/jwks.json
For better results, refresh your JWKS every 8 hours. If you can't find the{ "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" } ]}
idTokenVerify claims
To make sure that your token is valid, verify the token's following claims:- : expiration. The epoch timestamp when the token expires.
exp - : not before. The epoch timestamp when the token becomes valid.
nbf - (Optional) : the Unity Authentication user ID.
sub - (Optional) : the Unity project ID.
project_id - (Optional) : the unique token ID.
jti - (Optional) : the Issuer URL. The expected claim value is
iss.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 thesessionToken/authentication/anonymous/authentication/externalidTokenJSON object response example: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"}'
The response includes a different{ "userId": "T7galGM3T1Bggbb3FfNrzMdivZOG", "idToken": "eyJhbGciOiJSUzI1NiIsImt...Lc_RN4mn9Hq2k3tFOX5wukCganFjA", "sessionToken": "t1X_x7luG7uVvfTQKp6fd2f...MV6dSZWaJOHNymkmQ-es6qOkHF8", "expiresIn": 3599, "user": { "id": "T7galGM3T1Bggbb3FfNrzMdivZOG", "disabled": false, "externalIds": [] }}
sessionTokensessionTokenAuthorize 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 headerUnityEnvironmentidTokenidToken/anonymous/external-token/session-tokencurl -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:- : The HTTP status code.
status - : A custom error code defined by the authentication service.
title - : A message providing more details about the error returned.
detail
General errors
You might receive the following errors when making API calls to the Unity Authentication service:Status | Title | Detail | Troubleshooting |
|---|---|---|---|
| | N/A | Make sure that the |
| | | 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/external-tokenDetail | Description | Troubleshooting |
|---|---|---|
| Indicates that the token is invalid. | Refresh the external token, then sign in and link the token again. |
| 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. |
| 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. |
| 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. |