View as Markdown

Authentication

Live games typically use one of three authentication patterns:

  1. Authenticate directly with a social provider: The player signs in with Google, Meta, or another provider from the start.
  2. Link a social provider to an existing account: The player first signs in with their device ID, then later on links a social provider to that account.
  3. Re-authenticate and replace the existing session: A session (including those created by device ID) is already active, and the player re-authenticates with a social provider that’s linked to a different account.

This guide shows you how to implement each pattern in Hiro. The first two work the same as in vanilla Nakama, but the third requires more attention because of how NakamaSystem manages sessions internally.

Authenticate with a social provider #

Authenticating directly with a social provider works the same as in vanilla Nakama. See Authentication.

Call the appropriate LinkAsync method on the client. After linking, call RefreshAsync() to sync NakamaSystem’s cached account data. See Authentication: Link or unlink.

Replace an existing session #

Use this pattern when a session is already active and the player signs in with a social provider linked to a different Nakama account. This typically occurs when a player switches accounts, or when the game automatically authenticates by device ID on startup. For example, a returning player on a new device is signed in with a new device ID, so they need to re-authenticate with their social provider to retrieve their progress.

In vanilla Nakama, you own the session object, so signing in to a different account means overwriting your stored session tokens. In Hiro, NakamaSystem holds the session object on your behalf. Calling RefreshAsync() alone after re-authenticating won’t switch accounts as you expect. It only reloads data for the currently active session.

To replace the active session, you need to update the cached session tokens in place, and then refresh to load the new account’s data:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
var nakamaSystem = Instance.GetSystem<NakamaSystem>();

// Log out the current session.
await nakamaSystem.Client.SessionLogoutAsync(nakamaSystem.Session);

// Authenticate with the new provider to get the new session. This example authenticates with Facebook.
var newSession = await nakamaSystem.Client.AuthenticateFacebookAsync(facebookToken);

// Update the cached session tokens in place.
(nakamaSystem.Session as Session)?.Update(newSession.AuthToken, newSession.RefreshToken);

// Refresh to load the new account's data into NakamaSystem.
await nakamaSystem.RefreshAsync();

After RefreshAsync() completes, nakamaSystem.Session and nakamaSystem.Account reflect the new account.

Use this approach when the social provider is already linked to a different Nakama account. If the account doesn’t exist yet, link it instead. See Link or unlink.

See also #