Skip to content

Implement guest login

To implement guest login with the recipe code, complete the following procedure in order.

Before you begin, complete the common prerequisites.

Overall flow

What you configure and call in each step is as follows.

Step Category What you do
1 Hive Console Check the Client ID and enable guest login
2 Hive Axyl SDK Install the authentication module and the secure storage module
3 Hive Axyl SDK Initialize the SDK and register modules
4 Recipe code Copy the recipe folder
5 App code Prepare ClientId and DeviceKey
6 App code Prepare the guest credential store
7 Recipe code Call guest login
8 App code Handle login results
9 App code Verify the behavior
Save guest credentials before you check the result status

Even if the recipe fails while preparing the session after creating the account, it returns the guest credentials. If you save them only inside the success branch, you can no longer access the account that was already created.

1. Configure the Hive Console

  • Hive Console  Configure or check this in the Hive Console.

In the Hive Console, check the Client ID to use for login and enable guest login. If the login method is disabled, the recipe call is rejected.

Setting Required Where to check
Check the Client ID Required Get the security key
Enable guest login Required Check the login activation status in the console
Do not put the Client Secret in the app client

The recipe uses only the Client ID. If the Client Secret leaks from the app client, malicious users can call the API without authorization.

Apps that apply additional security to account creation cannot use this recipe as is, because GuestLoginRecipe does not accept the pre-approval value GrantKey. In this case, implement it by calling the Hive Axyl SDK methods directly, as described in guest account creation and guest login.

2. Install SDK modules

  • Hive Axyl SDK  Call the Hive Axyl SDK from the app.


    Detailed procedure: Install modules

Install the authentication module and the secure storage module in your Unity project. The secure storage module is used to encrypt and keep the DeviceKey and guest credentials on the device.

Package Needed Role
com.com2usplatform.hiveaxyl.core Required SDK initialization and login session management
com.com2usplatform.hiveaxyl.auth Required Guest account creation, guest login, and token issuance
com.com2usplatform.hiveaxyl.storage Recommended Encrypted storage of the DeviceKey and guest credentials

If your app already uses secure storage, you do not need to install com.com2usplatform.hiveaxyl.storage. Even in this case, the app must be able to read the DeviceKey and guest credentials again after it restarts.

3. Initialize the SDK

Initialize the SDK once at the app's entry point, and register the authentication, token, and secure storage modules. The recipe does not initialize the SDK, so calling it without initialization fails with a FailedPrecondition error.

The following example code registers the modules needed for guest login and initializes the SDK.

using Hive.Axyl.Auth;
using Hive.Axyl.Core;
using Hive.Axyl.Core.Unity;
using Hive.Axyl.Storage;

var config = CoreConfig.CreateBuilder("{appId}").Build();

HiveBootstrap.Initialize(config, builder =>
{
    builder
        .AddAuth()
        .AddToken()
        .AddSecureStorage();
});

For {appId}, enter the App ID you created in the Hive Console.

If you do not register AddAuth() and AddToken(), the recipe fails with a FailedPrecondition error. If your app uses another secure storage, you do not need to register AddSecureStorage().

4. Install the recipe code

  • Recipe code  Copy the recipe code into your project.

A recipe is source code that you copy into your project instead of installing as a package. Copy the following items from the axyl-samples-unity repository to Assets/Recipes/ in your Unity project.

The items to copy and their roles are as follows.

  • Recipes.asmdef: Common assembly definition for recipes
  • AssemblyInfo.cs: Setting that exposes internal helpers to other recipe assemblies
  • Helper/: Common code shared by multiple recipes
  • GuestLogin/: GuestLoginRecipe, GuestCredential, and result types

To call recipes from your app code, add the following assembly to references in your app's assembly definition. Because autoReferenced in the original Recipes.asmdef is false, your app assemblies do not reference it automatically.

{
  "name": "MyApp",
  "references": [
    "Hive.Axyl.Core",
    "Hive.Axyl.Auth",
    "Hive.Axyl.Storage",
    "Hive.Axyl.Samples.Recipes"
  ]
}

Replace MyApp with the assembly name your app uses, and keep your existing settings and references. Unity assemblies do not pass references on transitively, so you must list here every assembly that your app code uses directly. Hive.Axyl.Core contains CoreConfig and HiveError, Hive.Axyl.Auth contains AddAuth() and AddToken(), and Hive.Axyl.Storage contains AddSecureStorage(). If you do not register AddSecureStorage(), you do not need to list Hive.Axyl.Storage.

The code does not compile if you copy only GuestLogin/

GuestLoginRecipe uses the PKCE generation code and the session preparation code in Helper/. Copy Helper/, Recipes.asmdef, and AssemblyInfo.cs together.

5. Prepare ClientId and DeviceKey

  • App code  Implement this in the app.


    Detailed procedure: DeviceKey

The constructor of GuestLoginRecipe takes ClientId and DeviceKey. ClientId is the value you checked in step 1, which the Hive Console issues for each project. DeviceKey is the value the Hive Axyl authentication server uses to distinguish login sessions by device, and the app creates and keeps it itself.

The recipe does not create or save DeviceKey, so create and manage it according to the following conditions.

  • A different value for each device. A random value such as a UUID is recommended
  • A value created and saved once on first launch and reused for every later login
  • A length of 22 to 64 characters
  • A value made up only of ASCII characters, excluding spaces and control characters
Do not overwrite it with a new DeviceKey just because the storage could not be read

The value may not be gone; only the read may have failed. First fix the storage access problem or try reading again.

6. Prepare the guest credential store

The guest credential, GuestCredential, consists of PlayerId and GuestToken. You must keep these two values together so that the user logs in with the same guest account even after the app restarts.

GuestCredential.PlayerId and GuestCredential.GuestToken are the same as the values the Hive Axyl SDK calls GuestPlayerId and GuestToken. The recipe simply bundles the two values into one type and returns them.

The recipe does not save or delete guest credentials. Create a store component in your app that provides the following three operations.

Operation Return value Description
Load GuestCredential or null Reads the stored credential. Returns null if there is no value.
Save None Replaces the existing value with the GuestCredential it receives.
Delete None Deletes the stored credential. When the user links an external authentication provider such as Google or Apple to this account for the first time, the Hive Axyl authentication server invalidates the guest token, so delete it at that point.

For when to delete and the criteria for deciding, see the External authentication provider linking practical guide.

All three operations wait for storage access, so make them asynchronous methods that also take a CancellationToken. The example code below calls this store guestCredentialStore.

When the store does not work normally, handle each situation separately.

  • Storage access denied or a temporary failure: Provide a retry flow without deleting the stored value
  • Confirmed corruption of the stored data: Reset the storage, and then show the login method selection screen

Handle storage access denial and data corruption differently. If access is denied, the existing data may still remain, so you must not reset the storage.

7. Call guest login

  • Recipe code  Call the recipe code from the app.

Load the stored credential and pass it to LoginAsGuestAsync(). If the value is null, the recipe creates a new guest account; if there is a value, it restores the same account. If a Credential is returned, save it before you check Status.

Also prepare a CancellationTokenSource so that you can stop waiting when the user closes the screen or cancels login.

For the call that saves the Credential, pass CancellationToken.None instead of the login cancellation token. Even if the user cancels login after the account is created, the recipe returns the Credential for that account. If you pass the login cancellation token to the save call at this point, a store that checks the cancellation token ends the save without writing the value. The account then exists on the server, but no credential remains on the device. After the app restarts, the user cannot log in with that account.

The following example code loads the credential, logs in, and saves the returned credential regardless of login cancellation.

using System.Threading;
using Hive.Axyl.Samples.Recipes;

var recipe = new GuestLoginRecipe(clientId, deviceKey);

var cancellation = new CancellationTokenSource();
CancellationToken token = cancellation.Token;

GuestCredential storedCredential = await guestCredentialStore.LoadAsync(token);

LoginAsGuestOutcome outcome = await recipe.LoginAsGuestAsync(storedCredential, token);

if (outcome.Credential != null)
{
    // The account has already been created. Save it first, regardless of the result status.
    // Do not pass the login cancellation token, so that saving is not interrupted even if login is canceled.
    await guestCredentialStore.SaveAsync(outcome.Credential, CancellationToken.None);
}

If saving fails, keep outcome.Credential in memory and try saving again. If you discard this value before saving succeeds, you can no longer access the newly created guest account.

Call cancellation.Cancel() when the screen closes or the user chooses to cancel, and clean up with cancellation.Dispose() when the call finishes.

The recipe performs the following tasks internally.

Category Call Where to check
Recipe code Creates a pair of PKCE values and passes them separately to the login call and the token issuance call Prepare the call parameters
Hive Axyl SDK Creates a new guest account with CreateGuestAsync() Create a guest account
Hive Axyl SDK Restores the stored guest account with LoginGuestAsync() Log in as a guest
Hive Axyl SDK Exchanges the authorization code for an access token and a refresh token with IssueTokenAsync() Issue an access token and a refresh token
Hive Axyl SDK Activates the login session with SetSession() Activate the session

The recipe calls only one of CreateGuestAsync() and LoginGuestAsync(). Both calls return an authorization code, and the recipe uses that authorization code to continue through token issuance and session activation. When Success is returned, the session is already ready, so do not call the token issuance or session activation code separately.

The detailed procedures in the table above are written for calling the Hive Axyl SDK methods directly. Do not reimplement in the app the steps that the recipe handles for you, such as creating PKCE values. Refer to them only to check what each call sends and receives.

8. Handle login results

LoginAsGuestOutcome reports the login result through Status. FailedStep is a diagnostic value, so do not use it as the basis for branching the app's normal flow.

Status Value to check App handling
Success IsNewAccount, IsBlocked Check whether it is a new account, and if the account is not under a usage restriction, move to the post-login screen.
BusinessOutcome BusinessOutcome, UnknownOutcomeCode Branch according to the rejection reason, and handle and record unknown values as failures.
Failure Error.Code, Error.TraceId Record the technical problem, and provide a retry flow while keeping the credential.

IsBlocked is filled in only when an existing account is restored with a stored credential. Right after a new guest account is created, it is always false.

If you cancel login with a CancellationToken, Status becomes Failure and Error.Code becomes HiveErrorCode.Cancelled. If the account was created before the cancellation, Credential is returned as well, so save the credential even for a canceled result. For this save, do not pass the login cancellation token, as in the example code in step 7.

If the rejection reason is InvalidGuestToken, the user may have linked an external authentication provider to this account, which invalidated the guest token. In this case, guide the user to access the existing account with the linked login method. If you delete the stored credential in advance at the time of linking, this situation does not occur. For how to handle it, see the External authentication provider linking practical guide.

If the rejection reason is TemporarilyUnavailable, a token temporarily could not be issued. Save the returned Credential, and instead of creating a new account, log in again to the same account with that value.

Do not create a new account when login with a stored credential fails

If it is a temporary technical problem, you must try again with the same credential. If you create a new account automatically, it is separated from the progress of the existing account.

Do not show UnknownOutcomeCode and RawJson to users. Use them only when you need to record app errors, and do not assume that an unknown result is a known one.

9. Verify the behavior

  • App code  Verify the behavior in the app.

On a real device, verify new guest account creation and existing account restoration. In the Unity Editor, there is no device secure storage and ISecureStorage is not registered, so you cannot verify the save and restart flow as is.

  1. Run login with no stored guest credential.
  2. Check for Success and IsNewAccount == true, and check that GuestCredential was saved.
  3. Quit the app completely, and then run it again.
  4. Log in by passing the stored credential, and check for IsNewAccount == false.

Next steps

A guest account can be restored only with the credential stored on the device, so if the user deletes the app or changes devices, the user loses the account. To let users log in to the same account on other devices, see the External authentication provider linking practical guide.

To let logged-in users skip the login screen when they relaunch the app, see Automatic login.

To let users leave the logged-in account and log in with a different account, see the Logout practical guide.