Implement Google login
To implement Google login 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. Use the Credential Manager method on Android and the browser-based method on iOS, macOS, and Windows.
| Step | Category | What you do | Applies to |
|---|---|---|---|
| 1 | External console | Prepare the Google OAuth client | All |
| 2 | Hive Console | Enable Google login and register credentials | All |
| 3 | Hive Axyl SDK | Install the authentication module and the login Add-on | All |
| 4 | Hive Axyl SDK | Initialize the SDK and register modules | All |
| 5 | Recipe code | Copy the common and method-specific recipe folders | All |
| 6 | App code | Prepare the Hive Axyl ClientId and DeviceKey | All |
| 7 | Recipe code | Prepare the Google credential source | All |
| 8 | Recipe code | Call Google login | All |
| 9 | App code | Handle login results | All |
| 10 | App code | Verify the behavior | All |
Distinguish the three types of client IDs
The Web application type OAuth client ID in the Google Cloud Console, the Google OAuth client ID for the browser, and the Client ID in the Hive Console can be different values. Put the Web application type ID in Android Credential Manager. In the browser's WebAuthOptions.ClientId, put the ID of the Google OAuth client where you registered the corresponding redirect URI. In the ProviderLoginRecipe constructor, put the Hive Axyl Client ID.
1. Set up the Google external console
-
External console Configure this in the Google Cloud Console.
Detailed procedure: Check the Google login credentials
In the Google Cloud Console, prepare the OAuth client to use for Google login.
The Android and browser-based methods require different external console settings.
| Method | Values to prepare | Purpose |
|---|---|---|
| Android Credential Manager | Web application type OAuth client ID, Android type OAuth client | Pass the web client ID to the recipe. The Android client verifies the app by its package name and signature. |
| Browser web login session | Google OAuth client ID, authorization endpoint, redirect URI, Scope | Used when you create WebAuthOptions. You must also register the redirect URI in Authorized redirect URIs in the Google Cloud Console. |
If you do not specify tokenEndpoint in the browser-based method, the recipe calls ExchangeProviderTokenAsync() of the Hive Axyl SDK, and the Hive Axyl authentication server exchanges the authorization code with Google. To use this path, register the ID and Secret of the Google web application client in the Hive Console, and use the ID of the same client in the authorization URL as well. The Web Client Secret field in the Hive Console appears in the project's default settings when the project has a Windows App ID, and in the per-App ID settings when the runtime environment of the selected App ID is Windows. For App IDs that cannot meet these input conditions, use the public client path that specifies tokenEndpoint.
2. Configure the Hive Console
-
Hive Console Configure or check this in the Hive Console.
Detailed procedure: Google login credentials, Login method types
Register the Google login credentials and enable the login method. If the settings are empty or the login method is disabled, the recipe's Hive Axyl login step is rejected.
Configure the following items.
| Setting | Required | Where to check |
|---|---|---|
| Register the Google Web Client ID | Required | Google login credentials |
| Register the Google Web Client Secret | Required when you use the server exchange method | Google login credentials |
| Enable Google login | Required | Login method types |
| Per-App ID login settings | Optional | Per-App ID login settings |
Register the Web Client ID and Secret from the Google Cloud Console in the Hive Console. Do not confuse these values with WebAuthOptions.ClientId in the app code or the Hive Axyl ClientId. Do not include the Client Secret in the app code or the build output.
3. Install SDK modules and Add-ons
-
Hive Axyl SDK Call the Hive Axyl SDK from the app.
Detailed procedure: Install modules, Install the Google login Add-on
In your Unity project, install the Hive Axyl SDK modules required for Google login and the Add-ons for the methods you choose.
| Package | Needed | Role |
|---|---|---|
com.com2usplatform.hiveaxyl.core | Required | SDK initialization and common error handling |
com.com2usplatform.hiveaxyl.auth | Required | Login with Google credentials and token issuance |
com.com2usplatform.hiveaxyl.storage | Recommended | Encrypted storage of DeviceKey and session tokens |
com.com2usplatform.hiveaxyl.auth.addon.credentialmanager | Required for the Android Credential Manager method | Display of the Android account selection screen |
com.com2usplatform.hiveaxyl.auth.addon.webauth | Required for the browser-based method | Providing the browser web login session |
com.unity.nuget.newtonsoft-json | Required for the browser recipe | JSON processing in ProviderLogin.WebAuth/ |
If you use only the Android Credential Manager method, you do not need to install the WebAuth Add-on and the browser recipe. If you provide both methods, install both Add-ons. After you install the packages, you must also add the registration methods in Initialize modules.
4. Initialize the SDK
-
Hive Axyl SDK Call the Hive Axyl SDK from the app.
Detailed procedure: Initialize modules
At the app's entry point, register authentication, token, secure storage, and the login Add-ons you use, once. The recipe does not initialize the SDK.
The following example is an initialization that supports both the Android Credential Manager and browser-based methods.
using Hive.Axyl.Auth;
using Hive.Axyl.Auth.Addon.CredentialManager;
using Hive.Axyl.Auth.Addon.WebAuth;
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()
.AddCredentialManager()
.AddWebAuth();
});
For {appId}, enter the App ID you created in the Hive Console. If you support only one method, remove both the using directive and the registration method of the Add-on you do not use.
AddCredentialManager() registers the actual module only on Android, and AddWebAuth() registers the module on Android, iOS, macOS, and Windows. Neither method registers a module in the Unity Editor, and calling them on an unsupported OS does not cause an error.
5. 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
- ProviderLogin/:
ProviderLoginRecipe, result types, and the credential source contract - ProviderLogin.CredentialManager/:
GoogleCredentialManagerCredentialSource - ProviderLogin.WebAuth/:
GoogleCredentialSourceand common browser login code
If your app supports both methods, add the following assemblies to references in your app's assembly definition.
{
"name": "MyApp",
"references": [
"Hive.Axyl.Core",
"Hive.Axyl.Auth",
"Hive.Axyl.Auth.Addon.CredentialManager",
"Hive.Axyl.Auth.Addon.WebAuth",
"Hive.Axyl.Storage",
"Hive.Axyl.Samples.Recipes",
"Hive.Axyl.Samples.Recipes.ProviderLogin",
"Hive.Axyl.Samples.Recipes.ProviderLogin.CredentialManager",
"Hive.Axyl.Samples.Recipes.ProviderLogin.WebAuth"
]
}
Replace MyApp with the assembly name your app uses, and keep the existing settings and references. If you use only one method, you can remove the references to the Add-on and recipe assemblies you do not use. When you use ProviderLogin.WebAuth/, you must also install the com.unity.nuget.newtonsoft-json package.
Copy the common recipe folder as well
ProviderLogin.CredentialManager/ and ProviderLogin.WebAuth/ implement the credential source contract in ProviderLogin/, and ProviderLoginRecipe uses the common code in Helper/. Copy Helper/, Recipes.asmdef, AssemblyInfo.cs, and ProviderLogin/ together with the method-specific folders.
6. Prepare ClientId and DeviceKey
The ProviderLoginRecipe constructor takes ClientId and DeviceKey. ClientId is the value you checked in the common prerequisites, and the Hive Console issues it for each project. DeviceKey is the value the Hive Axyl authentication server uses to distinguish login sessions by device, and the app creates and stores it itself.
| Value | Where to put it | How to prepare |
|---|---|---|
Hive Axyl ClientId | new ProviderLoginRecipe(clientId, deviceKey) | Check it in Security Key in the Hive Console |
DeviceKey | new ProviderLoginRecipe(clientId, deviceKey) | Created and stored by the app |
| Google Web application type Client ID | GoogleCredentialManagerCredentialSource(webClientId) | Check it in the Google Cloud Console |
| Google OAuth Client ID | clientId of WebAuthOptions.Create() | Check it in the Google OAuth client where you registered the redirect URI |
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.
If ClientId or DeviceKey is empty, the recipe constructor throws ArgumentException. The web client ID for Android Credential Manager and the browser WebAuthOptions.ClientId must not be empty either.
You do not need to prepare PKCE or a nonce. The Google credential source creates and verifies the required values for each login attempt. In the browser-based method, separate PKCE values are used for Google and for the Hive Axyl authentication server, so do not pass values you created in the app to the recipe.
7. Prepare the Google credential source
- Recipe code Call the recipe code from the app.
Choose which method to log in with, create a credential source, and pass it to the recipe. For the credential source constructors and internal calls, see Get Google credentials.
7.1. Android Credential Manager method
Pass the Web application type OAuth client ID from the Google Cloud Console to GoogleCredentialManagerCredentialSource. The recipe creates a nonce and uses the id_token and UniqueId received from the Credential Manager account selection screen as the login credentials.
For {googleWebClientId}, enter the Web application type OAuth client ID, not the Android type OAuth client ID. UniqueId is used as the user identifier, not Id, which is the email address.
7.2. Browser-based method
Specify the Google OAuth client and the registered redirect URI in WebAuthOptions.Create(). If you omit tokenEndpoint as in the following example, the recipe exchanges the authorization code on the Hive Axyl authentication server through ExchangeProviderTokenAsync().
Specify tokenEndpoint only when you configure a public client to exchange the authorization code directly. If you specify the Google token endpoint, the recipe communicates directly with Google using PKCE and gets the user identifier from the id_token in the response.
On Windows, the WebAuth Add-on receives the callback at a local address whose port changes on every run. If the Google OAuth client allows redirects to local addresses with a variable port, specify a path such as /hive-auth/callback in WebAuthOptions.WithLoopbackRedirect() instead of WebAuthOptions.Create(). The recipe reserves a local address for each login and puts it in the authorization request. For the addresses to register in the Google Cloud Console, see Addresses to register in the allowlist. Settings created with WithLoopbackRedirect() work only on Windows, where a local address can be reserved.
If you also support the browser-based method on Android, the app can check the registered Add-ons to select the source.
using Hive.Axyl.Auth.Addon.CredentialManager;
using Hive.Axyl.Core;
using Hive.Axyl.Samples.Recipes;
IProviderCredentialSource source;
if (HiveCore.TryResolve<IAndroidCredentialManagerPlugin>(out _))
{
source = new GoogleCredentialManagerCredentialSource("{googleWebClientId}");
}
else
{
source = new GoogleCredentialSource(googleOptions);
}
If you provide only one method, call only that constructor without selecting a source for each OS. For the WebAuth Add-on's redirect URI and how to handle browser callbacks, see Web login session.
8. Call Google login
- Recipe code Call the recipe code from the app.
Pass the prepared credential source to LoginWithProviderAsync(). The recipe gets Google credentials and then continues through Hive Axyl login, token issuance, and session activation.
When the app must stop waiting, such as when it closes the login screen, call cancellation.Cancel(), and when the call finishes, clean up with cancellation.Dispose(). If the user closes the Google screen on Android, iOS, or macOS, do not call the cancellation token; handle the UserCanceled that the recipe returns instead.
On Windows, an external browser is used, so even if the user closes the browser, the recipe cannot detect it and keeps waiting. Add a cancel button to the login screen that calls cancellation.Cancel(), or specify a time limit such as new CancellationTokenSource(TimeSpan.FromMinutes(5)). To use TimeSpan, add using System;. For details, see the response status in Open a web login session.
The recipe performs the following tasks internally.
| Category | Call | Where to check |
|---|---|---|
| Recipe code | Check that the authentication, token, and session modules are registered | Initialize modules |
| Add-on | On Android, get the Google id_token with Credential Manager LoginAsync() | Android Google credentials |
| Add-on | In the browser-based method on Windows, reserve the local address that receives the callback with AllocateLoopbackRedirectUriAsync() | Prepare the redirect URI |
| Recipe code | Create the authorization URL, state, and Google PKCE for the browser-based method | Build the authorization URL |
| Add-on | In the browser-based method, open the Google login page with OpenAsync() and receive the callback | Open a web login session |
| Recipe code | Verify the callback state in the browser-based method | Check the callback |
| Hive Axyl SDK | If tokenEndpoint is left empty, exchange the browser authorization code with ExchangeProviderTokenAsync(). Put the redirect URI used in the authorization request in RedirectUri and the PKCE value for Google in CodeVerifier | Exchange external authorization codes |
| Recipe code | If tokenEndpoint is specified, exchange directly with the Google token endpoint | Browser-based method |
| Hive Axyl SDK | Pass the prepared Google credentials to LoginProviderAsync() | Log in with an external authentication provider |
| Hive Axyl SDK | Issue Hive Axyl tokens with IssueTokenAsync() and activate the session with SetSession() | Issue tokens and activate the session |
The recipe calls the SDK methods in the table above internally. If your app uses the recipe, do not call ExchangeProviderTokenAsync(), LoginProviderAsync(), IssueTokenAsync(), or SetSession() again. In the browser-based method, the PKCE for Google and the PKCE for Hive Axyl that the recipe creates are different values.
In the public client method with tokenEndpoint specified, the recipe sends the HTTP requests directly to Google. Even in this case, the Client Secret is not put in the app, and the app does not call a Hive Axyl Server API endpoint directly.
9. Handle login results
-
App code Implement this in the app.
Detailed procedure: HiveError information
Check Status of LoginWithProviderOutcome first, and then read the other values according to the status. FailedStep is a diagnostic value, so do not use it as a basis for branching in the normal flow.
Status | Value to check | App handling |
|---|---|---|
Success | PlayerId, IsBlocked | If the account is not under a usage restriction, go to the post-login screen. |
BusinessOutcome | BusinessOutcome, UnknownOutcomeCode | Branch according to the rejection reason, and treat unknown values as failures and record them. |
UserCanceled | None | The user closed the Google account selection screen or the browser authentication screen, or declined consent, so keep the login screen. |
Failure | Error.Code, Error.TraceId | Record the technical problem and offer a retry or another login method. |
The PlayerId in Success is the same value when the user logs in again with the same Google account. If IsBlocked is true, login succeeded but the account is under a usage restriction, so guide the user based on Usage restriction.
Distinguish UserCanceled from Cancelled in Failure. If the user closes the authentication screen or declines consent, the result is UserCanceled. If the app stops waiting with CancellationToken, the result is Failure with HiveErrorCode.Cancelled. On Windows, UserCanceled is not returned even if the user closes the browser, so the app must end the wait with its own cancellation handling.
| Situation | Recipe result | App handling |
|---|---|---|
| The user closes the account selection screen on Android | UserCanceled | Keep the login screen |
| The Android device has no Google account to request | Failure with Unavailable | Guide the user to add a Google account or use another login method |
| The user declines consent on the WebAuth screen | UserCanceled | Keep the login screen |
| The user closes the browser authentication screen on an OS other than Windows | UserCanceled | Keep the login screen |
The state of the browser callback differs from the current login request | Failure with PermissionDenied | The callback was not started by this login, so keep the login screen and let the user try again |
| Add-on not registered, incorrect redirect URI, or network problem | Failure | Record FailedStep and Error.TraceId, and check the settings or network status |
| The server rejects the Google credentials | BusinessOutcome or Failure | Check the Google console and Hive Console settings, and whether authentication has expired |
| The app cancels the wait | Failure with Cancelled | Clean up the in-progress login screen and keep the login screen |
BusinessOutcome can include values such as ProviderConfigNotFound, ProviderClientInfoNotExists, ProviderTokenError, InvalidAuthorizationCode, ExpiredAuthorizationCode, CodeChallengeMismatch, and TemporarilyUnavailable. The recipe combines the rejection reasons of multiple calls into one value, so check External authentication provider login response status and Issue an access token and a refresh token. If you use the server exchange, also check External authorization code exchange response status. Retry only TemporarilyUnavailable, with increasing intervals such as 1, 3, and 6 seconds. For the others, check the settings or authentication status first.
Do not leave the Google id_token, access tokens, authorization codes, or WebAuth callback URLs in logs, crash reports, or analytics events. Do not display UnknownOutcomeCode or RawJson to users; use them only when you need to record app errors.
10. Verify the behavior
- App code Verify the behavior in the app.
Credential Manager and WebAuth do not provide the actual authentication screen in the Unity Editor, so verify the behavior on supported devices and builds.
- Save the Google Cloud Console and Hive Console settings, and then build the app for the target OS.
- On Android, check that the Google account selection screen appears. On iOS, macOS, and Windows, check that the Google login page and the callback proceed normally.
- Check
SuccessandPlayerId, and check that the app moves to the post-login screen. - Quit the app completely, log in again with the same Google account, and check that
PlayerIdis the same. - On Android, iOS, and macOS, close the authentication screen and check that
UserCanceledis returned. On Windows, decline consent to checkUserCanceled, and check thatFailurewithCancelledis returned through the cancel button or the time limit.
Next steps
To let logged-in users skip the login screen when they relaunch the app, see Automatic login.
To link another login method to an account that is already logged in, see External authentication provider linking.
To leave the logged-in account and log in with another account, see Logout.