Skip to content

Log out

Log the currently logged-in user out of this device and remove the authentication state.

LogoutPlayerAsync() only requests logout from the server; it does not clear the in-memory session or the stored tokens of the app client. Access tokens that have already been issued remain valid after logout until they expire, so the app must check the result and clear the in-memory session and stored tokens itself. However, clear them only when the server has confirmed the logout.

1. Call the logout method

Method

LogoutPlayerAsync

Requests that the server end the login session of the calling device. Sessions on other devices logged in with the same account are kept.

Warning

A guest-only account is an account that has no login method linked other than guest. A guest-only account cannot log out, which prevents it from losing its login method afterward. If you try to log out a guest-only account, the GuestSignoutBlocked response is returned. When you receive this response, keep the active session and the saved credentials.

Call parameters

Field name Type Required Description
context ApiCallContext Optional Per-call settings object. If omitted, the default values are used.

Call example

For the result model and handling principles of common failures (Failure) that prevent the request from being performed, see Common error handling.

using Hive.Axyl.Auth;
using Hive.Axyl.Core;
using UnityEngine;

IAuthService auth = HiveCore.Resolve<IAuthService>();

AuthLogoutPlayerResult result = await auth.LogoutPlayerAsync();

switch (result)
{
    case AuthLogoutPlayerResult.Success:
        // Server logout succeeded → continue to local cleanup (steps 2-3).
        break;

    case AuthLogoutPlayerResult.GuestSignoutBlocked:
        // A guest-only account cannot log out (because the account could not be used again after logout).
        // Inform the user according to your policy.
        break;

    // Handle common Failure
    case AuthLogoutPlayerResult.Failure failure:
        HiveError err = failure.Problem;
        Debug.LogError($"[{err.Code}] {err.Message} (trace: {err.TraceId})");
        break;

    // Safety net: unhandled results and unknown new results (UnknownOutcome)
    default:
        Debug.LogWarning($"Unhandled result: {result.GetType().Name}");
        break;
}

Response data

No data is returned on success.

Response example

// AuthLogoutPlayerResult.Success does not return any Data.

Response status

We recommend handling the response cases of AuthLogoutPlayerResult with a switch statement.

For every result other than Success, keep the in-memory session and stored tokens. If the request fails because of a network error or timeout, you cannot tell whether the server processed the logout. If you delete the tokens at that point, you may lose any way to end the session that remains on the server, so keep the session and try logging out again.

Response case Description App client handling
Success The server logout request was processed successfully Delete the in-memory session and stored tokens in steps 2 and 3 below. Even if you canceled the request, delete them if the result is Success, because the server has already processed the logout.
GuestSignoutBlocked When a guest-only account cannot log out, which prevents it from losing its login method afterward Keep the active session and the saved credentials, and inform the user that logout was blocked.
PlayerNotFound When the account information cannot be found Check the server and product policies, and then handle it.
AppIdMismatch When the app in the X-App-Id header does not belong to the project of the current token Check the App ID setting used during SDK initialization and the project of the logged-in account
InvalidGatewayContext When the authentication context is missing or invalid Check that you registered the session through session activation
AppNotFound When the app information cannot be found Check the app registration status in the console
TerminateService When the app's service has been terminated Check the service operation status
UnknownOutcome A new result that this SDK version does not know Keep the session and stored tokens, and log it.
Failure Common Failure. Missing required parameters or format errors (invalid_parameter), missing required fields (missing_field), and a missing X-App-Id header (missing_app_id) also branch here, and the cause is contained in Failure.Problem.ExternalCode. See Common error handling. Keep the session and stored tokens. A canceled request also falls under this case. If it is a network error, try logging out again; handle other causes according to the common error handling guidelines.

2. Delete the in-memory session

Method

ClearSession

When the LogoutPlayerAsync() call succeeds, call ISessionManager.ClearSession() to reset the in-memory session of the app client. It resets all session fields to their default values and raises the OnSessionExpired event after cleanup. If there is no active session, it does nothing.

Call parameters

Field name Type Required Description
None - - No parameters. Get the session manager with HiveCore.Resolve<ISessionManager>() and call the method.

Call example

using Hive.Axyl.Core;

ISessionManager session = HiveCore.Resolve<ISessionManager>();

session.ClearSession();   // Reset the in-memory session → raises OnSessionExpired

Response data

No data is returned on success.

Response example

// ClearSession has no return value (void).
session.ClearSession();

Response status

ClearSession() does not return a result object. If there is no active session, it does nothing.

3. Delete stored tokens

Method

DeleteAsync

Call ISecureStorage.DeleteAsync() to delete items saved in secure storage key by key. Register the storage instance with AddSecureStorage as described in Register the secure storage module, and then get it with HiveCore.TryResolve<ISecureStorage>(out var storage). In environments where secure storage is not registered, such as the Unity Editor, this returns false; in that case there are no items to delete, so skip the deletion. Delete the tokens saved for automatic login with this method right after logout.

Call parameters

Field name Type Required Description
request SecureStorageDeleteRequest Required Request for the item to delete
cancellationToken CancellationToken Optional Cancellation token. If omitted, the default value is used.

SecureStorageDeleteRequest

Field name Type Required Description
Key string Required Key of the stored item to delete. This is the value the app chose when saving the token (the SDK does not define it).

Call example

using Hive.Axyl.Core;
using Hive.Axyl.Storage;
using UnityEngine;

// In environments without secure storage (such as the Editor), there is nothing to delete, so skip this step.
if (!HiveCore.TryResolve<ISecureStorage>(out var storage))
{
    return;
}

SecureStorageDeleteResult result =
    await storage.DeleteAsync(new SecureStorageDeleteRequest { Key = "hive.axyl.auth.access_token" });

switch (result)
{
    case SecureStorageDeleteResult.Success:
        // Deletion completed (also treated as Success when the key did not exist).
        break;

    case SecureStorageDeleteResult.AccessDenied:
        // Storage access denied — check the device security settings/permissions.
        break;

    case SecureStorageDeleteResult.DataCorrupted:
        // Stored data is corrupted — consider a full cleanup (ClearAsync).
        break;

    // Safety net: unhandled results and unknown new results (UnknownOutcome)
    default:
        Debug.LogWarning($"Unhandled result: {result.GetType().Name}");
        break;
}

Response data

No data is returned on success.

Response example

// Success branch example
// SecureStorageDeleteResult.Success does not return any Data.

Response status

Response case Description App client handling
Success Deletion completed. The result is Success even when the key did not exist. Proceed to delete the next key.
AccessDenied Storage access denied Check the device security settings/permissions.
DataCorrupted Stored data is corrupted Consider a full cleanup (ClearAsync).
Failure Common Failure. See Common error handling. Handle it according to the common error handling guidelines
UnknownOutcome Unknown new result As a safety net, log it and handle it conservatively.

Full flow example

Example code that handles logout, in-memory session deletion, and stored token deletion in order. It cleans up the in-memory session and stored tokens together only when logout succeeds.

Note

This example gets secure storage with HiveCore.TryResolve<ISecureStorage>(out var storage). This is because secure storage is not registered in the Unity Editor, so HiveCore.Resolve<ISecureStorage>() throws RegistrationNotFoundException. For the supported scope, see Register the secure storage module.

using Hive.Axyl.Auth;
using Hive.Axyl.Core;
using Hive.Axyl.Storage;
using System.Threading;
using System.Threading.Tasks;

public class LogoutFlow
{
    private readonly IAuthService _auth = HiveCore.Resolve<IAuthService>();
    private readonly ISessionManager _session = HiveCore.Resolve<ISessionManager>();

    public async Task<bool> SignOutAsync(CancellationToken ct = default)
    {
        var result = await _auth.LogoutPlayerAsync(new ApiCallContext { Token = ct });

        // For any result other than success (failure, cancellation, GuestSignoutBlocked, and so on), keep the session and
        // follow your retry/notification policy.
        if (result is not AuthLogoutPlayerResult.Success)
        {
            return false;
        }

        // The server has confirmed the logout, so finish the cleanup even if cancellation occurred in the meantime.
        _session.ClearSession();   // Remove the in-memory session → raises OnSessionExpired
        await DeleteStoredTokensAsync(CancellationToken.None);
        return true;
    }

    private async Task DeleteStoredTokensAsync(CancellationToken ct)
    {
        // In environments without secure storage (such as the Editor), there is nothing to delete, so skip this step.
        if (!HiveCore.TryResolve<ISecureStorage>(out var storage))
        {
            return;
        }

        // The keys below are examples of values the app chose when saving the tokens (the SDK does not define them).
        await storage.DeleteAsync(new SecureStorageDeleteRequest { Key = "hive.axyl.auth.access_token" }, ct);
        await storage.DeleteAsync(new SecureStorageDeleteRequest { Key = "hive.axyl.auth.refresh_token" }, ct);
        await storage.DeleteAsync(new SecureStorageDeleteRequest { Key = "hive.axyl.auth.player_id" }, ct);
        await storage.DeleteAsync(new SecureStorageDeleteRequest { Key = "hive.axyl.auth.expires_at" }, ct);
        await storage.DeleteAsync(new SecureStorageDeleteRequest { Key = "hive.axyl.auth.guest_token" }, ct);
        await storage.DeleteAsync(new SecureStorageDeleteRequest { Key = "hive.axyl.auth.guest_player_id" }, ct);
    }
}

This example uses the storage retrieved with HiveCore.TryResolve<ISecureStorage>(out var storage). When logout succeeds, it explicitly deletes the saved token keys right after calling ClearSession(). After the server confirms the logout, it does not pass the cancellation token to the token deletion, so no saved tokens remain even if cancellation is requested in the meantime.

Stored items and how to handle them at logout

ISessionManager manages only the in-memory session. Because a guest account cannot be reused after logout, when you log out, you must handle in-memory session cleanup and storage cleanup together instead of separately.

Stored item Purpose Recommended handling at logout
accessToken, refreshToken, playerId, expiresAtSec Automatic login session restoration Delete right after logout.
deviceKey Device identification Keep.
guestToken, guestPlayerId Guest session identification Delete right after logout.

Implementation checklist

  • Before calling logout, check whether an active session exists
  • Clean up the in-memory session and stored tokens only after confirming that logout succeeded
  • If logout fails because of a network error, keep the in-memory session and stored tokens and try logging out again
  • After logout, apply the in-memory session and stored token cleanup policies consistently instead of separately
  • If you use automatic login, verify that no stored tokens remain right after logout
  • Verify that guestToken and guestPlayerId are deleted right after logout