Unity Authentication sessions
This page describes the overall Unity Authentication flow from signing in, the token lifecycle, signing out, and general session management.
Signing in
When a player successfully logs in to a device for the first time, the Unity Authentication service grants a long-lived session token. Based on this session token it also grants an access token which is valid for 1 hour. The access token is used to authenticate the player when calling other Unity services. Both tokens are stored on the device using Unity Player Prefs and are associated with a player profile. For more details on player profiles, refer to the page on Profile management.
Token expiry and refreshing
In order to keep the player authorized beyond the 1 hour validity period of a single access token, the Unity Authentication service automatically attempts to periodically refresh the access token. If the refresh attempts fail before the expiration time, the access token expires and raises the Expired
event. Developers must handle this case and retry signing in for the player.
Note: The automatic access token refresh does not happen on Xbox®, PlayStation®, and Nintendo Switch®. On those platforms all token refreshes must be handled manually.
When the player signs in successfully the SignedIn
event is raised.
If a valid cached session token is available, then the SignInAnonymouslyAsync()
method refreshes the access token and session token, regardless of whether the player signed in anonymously or through a platform provider. If there is no player sign-in information, this method creates a new anonymous player. For more details see the section Sign in a cached player below.
Signing out
Calling AuthenticationService.Instance.SignOut
signs the player out by clearing the access token. By default the session token is retained. For details on clearing the session token see the section Clearing session tokens below.
When the player signs out successfully the SignedOut
event is raised.
A player who is signed out, or where the access token has expired, retains a valid session token. However they are no longer authorized to make calls to other Unity services until the access token has been refreshed or they sign in again.
using Unity.Services.Authentication;
void RegisterEvents()
{
AuthenticationService.Instance.SignedIn += () =>
{
Debug.Log($"The player has successfully signed in");
};
AuthenticationService.Instance.Expired += () =>
{
Debug.Log($"The access token was not refreshed and has expired");
};
AuthenticationService.Instance.SignedOut += () =>
{
Debug.Log($"The player has successfully signed out");
};
}
void CheckStates()
{
// this is true if the access token exists, but it can be expired or refreshing
Debug.Log($"Is SignedIn: {AuthenticationService.Instance.IsSignedIn}");
// this is true if the access token exists and is valid/has not expired
Debug.Log($"Is Authorized: {AuthenticationService.Instance.IsAuthorized}");
// this is true if the access token exists but has expired
Debug.Log($"Is Expired: {AuthenticationService.Instance.IsExpired}");
// this is true if the access token exists but is being refreshed
Debug.Log($"Is Refreshing: {AuthenticationService.Instance.IsRefreshing}");
}
Clearing session tokens
By default the SignOut
method will retain the session token. This allows the player to re-authenticate without needing to sign in again. If a different player signs in using an external provider, then their tokens will replace both the session and access token from the previous player.
Only in specific circumstances it is required to explicitly clear the session token. For example when you need to sign in as a new anonymous player, since SignInAnonymouslyAsync
will always try to use the existing persisted session token. In that scenario you need to either clear the current player's session token, or use a different profile. The session token can be cleared in two ways:
- set the optional
clearCredentials
parameter during sign out, as inAuthenticationService.Instance.SignOut(true)
. - if the player is already signed out, then the it can be cleared using
AuthenticationService.Instance.ClearSessionToken()
.
Clearing the session token deletes it from PlayerPrefs
.
Note: An anonymous account can be lost forever when clearing the session token if it has no linked platform account.
To verify if a session token is currently cached for the current profile, use AuthenticationService.Instance.SessionTokenExists
.
using Unity.Services.Authentication;
void SimpleSignOut()
{
// The session token will remain but the player will not be authenticated
AuthenticationService.Instance.SignOut();
}
void SignOutAndClearSession()
{
// The session token will be deleted immediately, allowing for a new anonymous player to be created
AuthenticationService.Instance.SignOut(true);
}
void SignOutThenClearSession()
{
AuthenticationService.Instance.SignOut();
// Do something else...
// Now clear the session token to allow a new anonymous player to be created
AuthenticationService.Instance.ClearSessionToken();
}
Sign in a cached player
A cached player is a player who has their session token persisted on the device. Every time a sign in is successful, the SDK caches a session token. A cached player exists if these conditions are fulfilled:
- The player previously signed in with Unity Authentication via anonymous login or platform login.
- The cached session token hasn't been deleted.
To verify if a session token is currently cached for the current profile, use AuthenticationService.Instance.SessionTokenExists
.
If the session token exists, then the SignInAnonymouslyAsync()
method recovers the existing credentials of a player, regardless of whether they signed in anonymously or through a platform account. A code example looks like this:
using Unity.Services.Authentication;
async Task SignInCachedUserAsync()
{
// Check if a cached player already exists by checking if the session token exists
if (!AuthenticationService.Instance.SessionTokenExists)
{
// if not, then do nothing
return;
}
// Sign in Anonymously
// This call will sign in the cached player.
try
{
await AuthenticationService.Instance.SignInAnonymouslyAsync();
Debug.Log("Sign in anonymously succeeded!");
// Shows how to get the playerID
Debug.Log($"PlayerID: {AuthenticationService.Instance.PlayerId}");
}
catch (AuthenticationException ex)
{
// Compare error code to AuthenticationErrorCodes
// Notify the player with the proper error message
Debug.LogException(ex);
}
catch (RequestFailedException ex)
{
// Compare error code to CommonErrorCodes
// Notify the player with the proper error message
Debug.LogException(ex);
}
}