Skip to content

Android Credential Manager login Add-on

An Add-on that displays the credential selection screen with AndroidX Credential Manager on Android and returns the credential that the app user selected. It shows the multiple options the app requested together on a single system selection screen. Pass the returned Google ID token and account identifier to LoginProviderAsync() of the Auth module to log in with a Google account.

Module information

  • Package: com.com2usplatform.hiveaxyl.auth.addon.credentialmanager
  • Interface: IAndroidCredentialManagerPlugin
  • Namespace: Hive.Axyl.Auth.Addon.CredentialManager
  • Registration method: AddCredentialManager()
  • Supported platforms: Android
  • Minimum requirements: Android API 29+, Unity 6000.0+

Registration and retrieval

Register it in the registration step of HiveBootstrap.Initialize, and then retrieve it with HiveCore.TryResolve<T>().

using Hive.Axyl.Auth;
using Hive.Axyl.Auth.Addon.CredentialManager;
using Hive.Axyl.Core;
using Hive.Axyl.Core.Unity;   // HiveBootstrap

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

if (HiveCore.TryResolve<IAndroidCredentialManagerPlugin>(out var credential))
{
    // Code that runs only in Android builds
}
Not registered in the Unity Editor

This Add-on is registered only in players built for Android. It is not registered in the Unity Editor even if you switch the platform to Android, so if you use HiveCore.Resolve<T>(), a RegistrationNotFoundException is thrown. Always check with TryResolve<T>() before you use it.

For the package installation and registration procedure, see Install and initialize the module.

Method summary

Asynchronous methods take CancellationToken ct = default as the last parameter. For the calling conventions, see Call context.

  • LoginAsync(): Display the credential selection screen and receive the credential that the app user selected
  • CancelCurrentSession(): Cancel an in-progress login from code

Methods

LoginAsync

Displays the credential selection screen with the CredentialOption items in the request as its options. Each option corresponds to one GetCredentialRequest.Builder().addCredentialOption() call, and the app user selects a credential on a single screen that combines all the options.

Only one login proceeds at a time. If you call it again while a login is in progress, it leaves the in-progress login as is and immediately returns a Failure whose Code is FailedPrecondition.

Task<AndroidCredentialManagerServiceLoginResult> LoginAsync(LoginRequest request, CancellationToken ct = default)

Result cases — AndroidCredentialManagerServiceLoginResult

Result case Wire code Description
Success — The app user selected a credential. Data.Selected contains the selected credential.
UserCanceled user_canceled The app user closed the credential selection screen.
NoCredentials no_credentials The device has no credential that matches the requested options. If you requested multiple options, this result is returned only when no credential matches any of the options. If you received this result after a request with FilterByAuthorizedAccounts set to true, change it to false and request again to show all Google accounts on the device.
UnknownOutcome UNKNOWN A new result that this SDK version does not recognize.
Failure FAILURE The call could not be completed. Check the cause with the HiveError in Problem.

UserCanceled implements IUserCanceledOutcome.

UserCanceled and NoCredentials are normal results, not Failure, so handle them separately from error handling. In contrast, if you cancel from code with CancellationToken or CancelCurrentSession(), the result is a Failure whose Code is Cancelled.

Do not log the raw response of the result

Every result that received a native response, including Success, contains the response body as is in RawResponse. For Success, this body contains the entire credential, including the ID token and the account's email address, so do not record it in logs, crash reports, or analytics events.

Exceptions

  • ArgumentNullException: When request is null
  • ArgumentException: When any of the following applies
    • request.Options is null or empty
    • Options contains a null item
    • Both GoogleId and SignInWithGoogle are specified in one option, or neither is specified
    • Two or more options of the same kind are included
    • WebClientId or Nonce of an option is null or empty

Call example

using Hive.Axyl.Auth.Addon.CredentialManager;

var request = new LoginRequest
{
    Options = new[]
    {
        new CredentialOption
        {
            GoogleId = new GoogleIdOption
            {
                WebClientId = "{webClientId}",
                Nonce = nonce,                      // Original nonce newly created for each login
                FilterByAuthorizedAccounts = true,  // Show as candidates only the Google accounts that authorized this app
            },
        },
    },
};

var result = await credential.LoginAsync(request);

if (result is AndroidCredentialManagerServiceLoginResult.Success success
    && success.Data.Selected.GoogleIdToken is { } google)
{
    string providerUserId = google.UniqueId;   // ProviderUserId of LoginProviderAsync
    string providerToken = google.IdToken;     // ProviderToken of LoginProviderAsync
}

When login succeeds, call LoginProviderAsync() with UniqueId as ProviderUserId and IdToken as ProviderToken.

Put UniqueId, not Id, in ProviderUserId

Id contains the account's email address, not the user identifier. The Hive Axyl authentication server compares ProviderUserId with the sub value of the validated ID token, so if you pass Id, the values differ and the login is rejected.

For the implementation procedure, see Get Google credentials on Android.

CancelCurrentSession

Cancels an in-progress login from code. The pending LoginAsync() ends with a Failure whose Code is Cancelled. If no login is in progress, it does nothing.

void CancelCurrentSession()

Data types

Credential

The credential that the app user selected. Check which of the properties for each credential type contains a value, and use that one.

Field Type Required Description
GoogleIdToken GoogleIdTokenCredential? Optional Google ID token credential.

CredentialOption

A single option to present on the selection screen. Specify exactly one of GoogleId and SignInWithGoogle. If you specify both or neither, an ArgumentException is thrown.

Field Type Required Description
GoogleId GoogleIdOption? Optional Option that lets the user choose a Google account in the account selection sheet.
SignInWithGoogle SignInWithGoogleOption? Optional Option presented as a Sign in with Google button flow.

GoogleIdOption

Option that lets the user choose a Google account in the account selection sheet. Corresponds to GetGoogleIdOption.Builder.

Field Type Required Description
WebClientId string Required OAuth 2.0 client ID of the Web application type. It becomes the value of the aud claim of the issued ID token, and it is different from the Android type client ID. For how to issue it, see Check the Google login credentials.
Nonce string Required Original nonce that the app created with a cryptographically secure random number generator. A URL-safe Base64 string without padding is recommended. The Add-on passes this value as is, and Google puts the same string in the nonce claim of the ID token. Unlike the Apple login Add-on, no SHA256 hash is applied.
FilterByAuthorizedAccounts bool Required If true, only Google accounts that the app user previously authorized for this app are shown as candidates; recommended for the first attempt. If false, all Google accounts on the device are shown.
AutoSelectEnabled bool Required Whether to return immediately without the selection screen when only one account has been authorized. Applies only when FilterByAuthorizedAccounts is true.
RequestVerifiedPhoneNumber bool Required Whether to also receive a verified phone number as GoogleIdTokenCredential.PhoneNumber. It is returned only in the sign-up flow where FilterByAuthorizedAccounts is false, and you must get scope approval in Google Cloud Console. For an account without a verified phone number, an empty string is returned without an error.
HostedDomainFilter string Required Restricts candidate accounts to a specific Google Workspace hosted domain. An empty string means no restriction.

GoogleIdTokenCredential

Original fields of the credential issued by Google. The Add-on does not validate the signature, aud, iss, or nonce of the ID token. All fields are information that identifies the user, so they are not written to SDK logs in plain text.

Field Type Required Description
Id string Required The account's email address, not a user identifier. Google has deprecated this field, so use UniqueId for ProviderUserId and Email for the email address.
IdToken string Required OpenID Connect ID token in JSON Web Token (JWT) format. Use it as ProviderToken in the LoginProviderAsync() request.
DisplayName string Required Display name. Empty string if the scope was not granted.
GivenName string Required Given name. Empty string if the scope was not granted.
FamilyName string Required Family name. Empty string if the scope was not granted.
ProfilePictureUri string Required Profile picture URL. Empty string if there is no value.
PhoneNumber string Required Verified phone number. Meaningful only when RequestVerifiedPhoneNumber is true; empty string if it was not requested or the account does not support it. Google has deprecated this field without a replacement.
UniqueId string Required Unique identifier of the Google account that the Google Identity SDK read from the sub value of the ID token. Use it as ProviderUserId in the LoginProviderAsync() request; a successful credential always has a value.
Email string Required The account's email address read from the ID token. Use it only for display or account hints, not as an identifier. Empty string if the credential has no email address.

LoginRequest

Field Type Required Description
Options IReadOnlyList<CredentialOption> Required List of options to present on the selection screen. It must contain at least one option, and include only one option of each kind.

LoginResponse

Field Type Required Description
Selected Credential Required The credential that the app user chose on the selection screen. A credential selected automatically without the selection screen through AutoSelectEnabled is also contained here.

SignInWithGoogleOption

Option presented as a Sign in with Google button flow. Corresponds to GetSignInWithGoogleOption.Builder.

Field Type Required Description
WebClientId string Required Same value as GoogleIdOption.WebClientId.
Nonce string Required Follows the same rules as GoogleIdOption.Nonce.
HostedDomainFilter string Required Restricts candidate accounts to a specific Google Workspace hosted domain. An empty string means no restriction.