Skip to content

Implement logout

To implement logout with the recipe code, complete the following steps 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 Axyl SDK Install the authentication module and the secure storage module
2 Hive Axyl SDK Initialize the SDK and register modules
3 Recipe code Copy the recipe folders
4 App code Connect the logout button and cancellation handling
5 Recipe code Call logout
6 App code Handle results and saved information
7 Hive Axyl SDK, App code Delete the tokens saved on the device
8 App code Verify the behavior
Delete saved information and move between screens based on SessionCleared

Status tells you only how the request ended. SessionCleared tells you whether the login session on the current device was actually cleared, so do not treat the two values as having the same meaning.

1. 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 delete the tokens saved on the device after logout.

Package Needed Role
com.com2usplatform.hiveaxyl.core Required SDK initialization and management of the current login session
com.com2usplatform.hiveaxyl.auth Required Logout requests
com.com2usplatform.hiveaxyl.storage Recommended Deleting the tokens used for automatic login

If your app already uses a secure store, you do not need to install com.com2usplatform.hiveaxyl.storage. Even in this case, you must be able to delete the information used for automatic login right after logout.

2. Initialize the SDK

Initialize the SDK once at the app's starting point, and register the authentication module and the secure storage module. The recipe does not initialize the SDK, so if you call it without initializing the SDK, it fails with a FailedPrecondition error.

The following example code registers the modules needed for logout 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();
});

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

If you do not register AddAuth(), the recipe fails with a FailedPrecondition error. The logout recipe does not use AddToken() in the example above, but it is registered as well because login needs it. If you have already completed initialization in the login step, do not call it again.

3. 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
  • Logout/: LogoutRecipe and result types

To call recipes from your app code, add the following assemblies 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 the 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 Logout/

LogoutRecipe uses the result classification code in Helper/. Copy Helper/, Recipes.asmdef, and AssemblyInfo.cs together.

4. Connect the logout button and cancellation handling

  • App code  Implement this in the app.

Lock the logout button when it is selected so that duplicate requests do not occur, and prepare a cancellation token so that you can stop waiting when the screen closes.

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

private readonly LogoutRecipe m_logoutRecipe = new LogoutRecipe();
private CancellationTokenSource m_logoutCancellation;

private void CancelLogout()
{
    m_logoutCancellation?.Cancel();
}

LogoutRecipe takes no constructor arguments. Create it once in the screen component and reuse it.

5. Call logout

  • Recipe code  Call the recipe code from the app.

When the button is selected, call LogoutAsync(). The recipe requests logout from the server and, if the request succeeds, also cleans up the in-memory session on the current device.

var cancellation = new CancellationTokenSource();
m_logoutCancellation = cancellation;

try
{
    SetLogoutButtonEnabled(false);

    // Remember the account to log out so that step 7 can delete only this account's saved information.
    long playerId = HiveCore.Resolve<ISessionManager>().PlayerId;

    LogoutOutcome outcome = await m_logoutRecipe.LogoutAsync(cancellation.Token);

    WriteLogoutLog(outcome);
    await HandleLogoutOutcomeAsync(outcome, playerId);
}
finally
{
    cancellation.Dispose();
    m_logoutCancellation = null;
    SetLogoutButtonEnabled(true);
}

SetLogoutButtonEnabled, WriteLogoutLog, and HandleLogoutOutcomeAsync are methods that the app implements. Result handling continues in step 6.

The recipe performs the following tasks internally.

Category Call Where to check
Hive Axyl SDK Request logout from the server with LogoutPlayerAsync() Call the logout method
Hive Axyl SDK Clean up the in-memory session with ClearSession() Delete the in-memory session

Before sending the request, the recipe first checks that the authentication feature and the session management feature are registered and that there is a login session to end. If any of these is not ready, it returns a FailedPrecondition error without calling the server.

The recipe remembers the access token from before it requests logout, and when the response comes back, it calls ClearSession() only if the session is unchanged. If the user logged in again and a new session came in while the request was pending, the recipe does not delete that session.

The recipe does not delete the tokens saved on the device. The app handles the deletion directly in step 7.

6. Handle results and saved information

Delete the saved information and go to the login screen only when SessionCleared is true. If you branch by looking only at Status, you lose the saved information while the session still remains.

Status of LogoutOutcome has three values: Success, BusinessOutcome, and Failure. The BusinessOutcome property is meaningful only when Status is BusinessOutcome. The rejection reasons the server returns include, in addition to GuestSignoutBlocked, service termination, app information mismatch, and account lookup failure, so check the full list in the detailed procedure above.

Condition Current state App handling
SessionCleared == true The login session on the current device has been cleared Delete the saved automatic login information, and then go to the login screen.
SessionCleared == false and Status == Success The session changed because the user logged in again or the tokens were refreshed during the request Do not move to another screen. Update the saved information with the current session values held by ISessionManager.
SessionCleared == false and BusinessOutcome == GuestSignoutBlocked The guest account's login session is kept Keep the saved information, and inform the user that guest accounts cannot log out.
SessionCleared == false and Status == Failure The login session is kept Keep the saved information, and display an error message or a retry screen.
SessionCleared == false and other rejection reasons The login session is kept Keep the saved information, and display a message that matches the rejection reason.
Guest accounts cannot log out

A guest account that has no other login method linked loses any way to log in again if it logs out. So the server rejects the logout and returns GuestSignoutBlocked. This is a policy, not an error, so if you provide the logout button to guest accounts as well, you must handle this result.

If you cancel the cancellation token, Status becomes Failure and Error.Code becomes HiveErrorCode.Cancelled. Even then, if the server has already ended the session and the session did not change in the meantime, SessionCleared comes back as true, so check SessionCleared in cancellation results as well.

Use Error, FailedStep, UnknownOutcomeCode, and RawJson only for app logs and diagnostics. Display easy-to-understand messages defined by the app to users, and do not log tokens.

7. Delete the tokens saved on the device

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

    App code  Implement this in the app.


    Detailed procedure: Delete stored tokens

If SessionCleared is true, delete the tokens used for automatic login from the device. The recipe cleans up only the in-memory session, so if you leave these values, the app logs in again with the logged-out account on the next launch.

7.1. Information to delete

The only values to delete are the automatic login information of the logged-out account. Delete them only when the PlayerId you remembered in step 5 is the same as the PlayerId in the saved automatic login information.

How to handle each stored item is as follows.

  • Automatic login information of the logged-out account: Delete
  • DeviceKey: Keep. A value that distinguishes login sessions by device, not by account
  • Guest credentials: Keep. If you delete them, you cannot log in to that guest account again

7.2. How to delete and handle failures

Apps that use com.com2usplatform.hiveaxyl.storage delete stored items by key with ISecureStorage.DeleteAsync(). If the app uses a store it prepared itself, use that store's deletion method as is.

If the deletion fails, guide the user to retry on the login screen. If automatic login runs before the deletion is complete, the user enters an account they did not intend to use.

8. Verify the behavior

  • App code  Verify the behavior in the app.

Verify the logout behavior with a regular account, a guest account, a communication failure, and a cancellation.

The results to check in each situation are as follows.

  • Logout from a regular login account: SessionCleared is true, and the app goes to the login screen after the saved automatic login information is deleted
  • Logout from a guest account: Check GuestSignoutBlocked and SessionCleared == false, and keep the current screen and the saved information
  • Communication failure during logout: Check SessionCleared == false, and display the retry screen while keeping the current session
  • Canceling the logout request: Handle the saved information and the screen based on SessionCleared, regardless of Status

Next steps

To also provide a flow in which users delete the account itself, see Delete an account.