skip to content

With Credential Manager on Android, how do you implement Sign in with Google, and what should the app do when getCredential throws NoCredentialException?

level: seniorimportance: should knowfreq 45%

answer

  1. GetGoogleIdOption in a GetCredentialRequest
  2. authorized accounts first
  3. CustomCredential becomes GoogleIdTokenCredential
  4. the ID token goes to your server

basics

~20 s

Wrap a GetGoogleIdOption in a GetCredentialRequest, call CredentialManager.getCredential, turn the returned CustomCredential into a GoogleIdTokenCredential and send its idToken to the server to verify. On NoCredentialException, retry without authorized-account filtering to offer sign-up, then fall back to regular sign-in.

solid answer

~30 s

Add `androidx.credentials:credentials` 1.6.0, `credentials-play-services-auth` and `googleid` 1.2.1. Build a `GetGoogleIdOption` with `setServerClientId` (your server's OAuth client ID), `setFilterByAuthorizedAccounts(true)`, `setAutoSelectEnabled(true)` and a server nonce. Put it in a `GetCredentialRequest` and call the suspending `getCredential(activityContext, request)`. If the result is a `CustomCredential` of type `GoogleIdTokenCredential.TYPE_GOOGLE_ID_TOKEN_CREDENTIAL`, use `GoogleIdTokenCredential.createFrom(credential.data)` and send `idToken` to the backend, which verifies it. `NoCredentialException` means no viable credential: retry with `setFilterByAuthorizedAccounts(false)` for sign-up, then show your normal sign-in screen. Treat `GetCredentialCancellationException` as the user saying no, and keep a Sign in with Google button, built with `GetSignInWithGoogleOption`, for accounts the bottom sheet excludes. On sign-out call `clearCredentialState`.

code

kotlin · 30 lines
kotlin
suspend fun googleIdToken(activity: Activity, serverClientId: String, nonce: String): String? {
    val credentialManager = CredentialManager.create(activity)

    suspend fun attempt(authorizedOnly: Boolean): GetCredentialResponse {
        val googleIdOption = GetGoogleIdOption.Builder()
            .setFilterByAuthorizedAccounts(authorizedOnly)
            .setServerClientId(serverClientId)
            .setAutoSelectEnabled(authorizedOnly)
            .setNonce(nonce)
            .build()
        val request = GetCredentialRequest.Builder()
            .addCredentialOption(googleIdOption)
            .build()
        return credentialManager.getCredential(activity, request)
    }

    val response = try {
        attempt(authorizedOnly = true) // returning users
    } catch (e: NoCredentialException) {
        attempt(authorizedOnly = false) // sign-up: offer every Google account on the device
    }

    val credential = response.credential
    if (credential is CustomCredential &&
        credential.type == GoogleIdTokenCredential.TYPE_GOOGLE_ID_TOKEN_CREDENTIAL
    ) {
        return GoogleIdTokenCredential.createFrom(credential.data).idToken // verify on the server
    }
    return null
}

go deeper

for a junior

Recall the shape: an option in a request, getCredential, a Google ID token credential, and the token sent to the server.

for a middle

Explain authorized-accounts filtering, auto-select, the CustomCredential type check and createFrom, and why the server client ID is used.

for a senior

Handle each failure: NoCredentialException into sign-up, cancellation as a user choice, configuration errors, and the button flow for accounts the bottom sheet excludes.

for a principal

Decide how Google sign-in sits beside passkeys, passwords and a path for devices without Google Play services, and how account linking stays consistent across them.

## The pieces **Sign in with Google** on Android now goes through **Credential Manager**, the Jetpack API that Google positions as the replacement for the legacy Google Sign-In, One Tap and Smart Lock for Passwords APIs. You need three artifacts: - `androidx.credentials:credentials` (1.6.0 at the time of writing): the `CredentialManager` API itself; - `androidx.credentials:credentials-play-services-auth`: the provider library that hands requests to Google Play services (on Android 13 and lower it is the only provider path; Android 14 and higher also has providers registered with the system); - `com.google.android.libraries.identity.googleid:googleid` (1.2.1): the Google-specific options and the `GoogleIdTokenCredential` type. You also configure the Google Auth Platform in your Cloud project. Its OAuth **client ID for your server** is what you pass as `serverClientId`, because the ID token is minted for your backend. Brand verification makes your app name visible on the consent screen. ## The bottom-sheet flow, step by step 1. Build a **`GetGoogleIdOption`**: `setServerClientId(...)`, `setFilterByAuthorizedAccounts(true)` to offer only accounts that already used your app, `setAutoSelectEnabled(true)` for automatic sign-in of a returning user, and `setNonce(...)` with a server-issued value. 2. Wrap it in `GetCredentialRequest.Builder().addCredentialOption(option).build()`. 3. Call the suspending `CredentialManager.create(context).getCredential(activityContext, request)`. It shows the bottom sheet, which needs an activity context to launch its UI. 4. Read `response.credential`. For Google it arrives as a **`CustomCredential`** whose `type` is `GoogleIdTokenCredential.TYPE_GOOGLE_ID_TOKEN_CREDENTIAL`. Turn it into a `GoogleIdTokenCredential` with `GoogleIdTokenCredential.createFrom(credential.data)`. 5. Send its **`idToken`** to your backend, which verifies the token (signature, audience, nonce) before creating a session. Profile fields such as the display name are for the UI, not for identity. ## The exceptions and what each one means | Exception from `getCredential` | Meaning | What the app does | |---|---|---| | `NoCredentialException` | No viable credential, or the user didn't consent to any | With authorized-only filtering, retry with `setFilterByAuthorizedAccounts(false)` to offer sign-up; otherwise show your regular sign-in screen | | `GetCredentialCancellationException` | The user deliberately dismissed the UI | Don't re-prompt at once; leave the Sign in with Google button available | | `GetCredentialProviderConfigurationException` | Provider set-up mismatch, typically a missing provider dependency or a system service that isn't enabled | Check the `credentials-play-services-auth` dependency; treat the device as unable to offer this path | | `GetCredentialInterruptedException` | The operation was interrupted | Retry | | `GetCredentialUnsupportedException` | The request isn't supported, for example combining the button option with others | Fix the request | ## Bottom sheet and button Google recommends offering both a **bottom sheet** (which can also list passkeys and passwords) and a distinct **Sign in with Google button**, because they cover different gaps: - The bottom sheet is dismissible; the button lets the user restart the flow without restarting the app. - The bottom sheet **excludes accounts that need re-authentication**; the button flow can reach them. - With **no Google account on the device** the bottom sheet does not appear at all; the button lets the user add one. - A user who turns off **"Sign-in prompts"** in their Google Account settings suppresses the bottom sheet for every account. The button uses **`GetSignInWithGoogleOption.Builder(serverClientId)`**, optionally with `setNonce` and `setHostedDomainFilter`. That option **cannot be combined with other options** in one request; the Play services provider rejects it with `GetCredentialUnsupportedException`. ## Why the nonce and server verification matter - The ID token is a signed statement from Google that this account signed in to **your server's** client ID. Only the server can turn it into a session safely. - A **nonce** issued by your server and passed with `setNonce` comes back inside the token, so the server can reject a token captured from an earlier sign-in. - Anything else the app forwards, such as the email or display name read on the device, can be forged by a modified client. ## Signing out and edges - On sign-out, call `clearCredentialState(ClearCredentialStateRequest())`. Providers may hold an active credential session that would otherwise steer the next sign-in back to the same account. - If your backend uses Firebase Authentication, the ID token is exchanged for a Firebase credential. That exchange belongs with Firebase Authentication; the Credential Manager side ends at the ID token. - Credential Manager's Sign in with Google works on Android 4.4 (API level 19) and higher, but the Google path still depends on Google Play services, so plan another sign-in method for devices without it. - Never trust an ID token that only the client has checked.

  • Users report the Google bottom sheet never appears for them, yet the Sign in with Google button works; what explains it?
    The bottom sheet excludes accounts that need re-authentication and does not appear when the device has no Google account. It is also suppressed for every account when the user turns off "Sign-in prompts" in Google Account settings. The button flow, `GetSignInWithGoogleOption`, still works in these cases, which is why Google recommends shipping both.
  • Why must GetSignInWithGoogleOption go in a request of its own?
    The Play services provider accepts it only as the single option in a `GetCredentialRequest`. Combined with a password, passkey or `GetGoogleIdOption`, the request fails with `GetCredentialUnsupportedException`. Use it for the explicit button, and the combined bottom-sheet request for the passive prompt.

  • NoCredentialException means Google Play services is missing, so Google sign-in must be disabled.
  • The app can trust the email in GoogleIdTokenCredential without sending the ID token to its server.
  • GetSignInWithGoogleOption can be combined with password and passkey options in one request.
  • serverClientId should be the Android client ID, since the token is consumed by the app.
  • After sign-out nothing needs to be cleared because Credential Manager keeps no session.

Assumes Credential Manager 1.6.0 with googleid 1.2.1; Credential Manager replaces the legacy Google Sign-In, One Tap and Smart Lock for Passwords APIs.