> ## Documentation Index
> Fetch the complete documentation index at: https://auth0.com/llms.txt
> Use this file to discover all available pages before exploring further.

> Learn how you can implement Sign In with Google for native mobile applications.

# Add Sign In with Google to Native Android Apps

[Sign in with Google](https://developers.google.com/identity/gsi/web/guides/overview) allows users to authenticate with an active Google Account, providing users with a seamless login experience for your application. You can implement this feature for your native Android applications using the Credential Manager for Android with Auth0.

Review the sections below to learn more about the steps and methods required for configuring Sign in with Google.

## How it works

This feature uses Android's Credential Manager to facilitate Sign in with Google in your Auth0-protected Android application. The steps below demonstrate the general user workflow for Sign in with Google.

<Frame>
  <img src="https://mintlify.s3.us-west-1.amazonaws.com/auth0/docs/images/cdy7uua7fh8z/6WofMhOOH7GU0NwEcyebiZ/4d4adcb20b74215c7026c1bc9c95be6c/Google_Sign_In_diagram.png" alt="" />
</Frame>

1. A user opens your Android application and chooses to log in with Google.
2. Your Android application uses the Credential Manager to request Sign in with Google.
3. On the account selection prompt, the user chooses their preferred Google account.
4. Google signs the user in locally and handles all authentication.
5. The user completes sign-in with no additional interaction required.
6. Google returns an `id_token` to your Android application.
7. Your Android application sends the `id_token` to your Auth0 tenant for validation. Auth0 validates the `client_id` from the `id_token` against the `client_id` of the Google social connection configured in your tenant.
8. The Auth0 server returns an `access_token` to your Android application.

## Before you begin

Before you begin configuring Sign in with Google, ensure the following are true:

* A [Google social connection](https://marketplace.auth0.com/integrations/google-social-connection) has been set up within your Auth0 tenant.
  * For the **Purpose** setting, enable the connection for Authentication, Connected Accounts for Token Vault, or both. To learn more, read [User authentication vs Connected Accounts](/docs/secure/tokens/token-vault/connected-accounts-for-token-vault#user-authentication-vs-connected-accounts).
* Sign in with Google has been added to your Android application using [Android's Credential Manager](https://developer.android.com/identity/sign-in/credential-manager-siwg).

## Configuring Sign in with Google for Android applications

Implementing Sign in with Google involves three primary steps:

1. Creating credentials in Google Cloud Console.
2. Configuring application details in Auth0.
3. Updating code in your Android application.

The sections below provide technical details for each of these steps.

### Create Credentials in the Google Cloud Console

To get started, you must first configure the following items in your Google Cloud Console:

1. Create an OAuth 2.0 credential with the type set to `Android`. This is referred to as `client_id_native`.
2. Add the SHA1 hash for the native application to the Android Client from Step 1.

   * Google currently only supports SHA1.
3. Create an additional OAuth client for web (`client_id_web`).

   * In some scenarios, you may have already configured this item for your social connections that support web-based Sign in with Google.

<Callout icon="file-lines" color="#0EA5E9" iconType="regular">
  You cannot use Google Credential Manager with the Android `client_id` or an error will occur. In the ID Token returned from Google, the authorized party (azp) is automatically set to the Android OAuth Client ID, and the audience (aud) is set to the Web OAuth Client ID.

  When invoking the Credentials Manager from Android, the native application should use the `client_id_web` via `.setServerClientId` in the Credentials Manager SDK. `client_id_web` corresponds to the Web Application OAuth 2 Credential in the Google Cloud Console, and it is configured in the Google OAuth2 social connection. For more information, refer to [Google’s documentation](https://developer.android.com/training/sign-in/credential-manager).
</Callout>

### Configure Auth0

The Sign in with Google flow leverages the <Tooltip tip="OAuth 2.0: Authorization framework that defines authorization protocols and workflows." cta="View Glossary" href="/docs/glossary?term=OAuth+2.0">OAuth 2.0</Tooltip> Token Exchange, which occurs between Auth0 and your Android application.

After creating your credentials in the Google Cloud Console, you can enable Sign in with Google using the Credential Manager for Android. To do so, update your application through either the <Tooltip tip="Auth0 Dashboard: Auth0's main product to configure your services." cta="View Glossary" href="/docs/glossary?term=Auth0+Dashboard">Auth0 Dashboard</Tooltip> or the <Tooltip tip="Management API: A product to allow customers to perform administrative tasks." cta="View Glossary" href="/docs/glossary?term=Management+API">Management API</Tooltip>.

<Tabs>
  <Tab title="Auth0 Dashboard">
    To update the application through the Auth0 Dashboard, follow the steps below:

    1. Navigate to [Applications > Applications](https://manage.auth0.com/#/applications) and choose your native Android application.
    2. On the **Settings** tab, expand the **Advanced Settings** section.
    3. Select the **Device Settings** tab and activate the **Enable Sign in with Google (Android 4.4+) using Credentials Manager** setting.
    4. **For new applications**: On the Device Settings tab, complete the fields in the **Android** section, including **App Package Name**. For more information, review [Enable Android App Links Support](/docs/get-started/applications/enable-android-app-links-support).
    5. Select **Save Changes**.
  </Tab>

  <Tab title="Management API">
    To update your application through the Management API, call the [Update a client](https://auth0.com/docs/api/management/v2/clients/patch-clients-by-id) endpoint as follows:

    ```json lines theme={null}
    PATCH /api/v2/clients/{id}

    { 
      "native_social_login": { 
        "google": { 
          "enabled": true 
        } 
      },
      "mobile": {
        "android": {
          // Update this to reflect the bundle identifier of your App
          "app_package_name": "com.yoursite.yourapp"
        }
      }
    }
    ```
  </Tab>
</Tabs>

### Update code in the Android application

The following example can complement the web flow used for non-Google authentications, such as Microsoft, username and password, or enterprise federations.

```go lines theme={null}
auth0Client.loginWithNativeSocialToken(
  googleCredential.idToken.toString(),
  "http://auth0.com/oauth/token-type/google-id-token")
    .validateClaims()
    .setScope("openid profile email")
    .start(object: Callback < Credentials, AuthenticationException > {
      override fun onFailure(error: AuthenticationException) {
        showSnackBar("Failure a0: $error")

      }

   override fun onSuccess(auth0Creds: Credentials) {
    // Logic to Handle credentials
    }
    })
```

Obtaining the Google `googleCredential` requires the native application code to invoke the Google library. For details, refer to [Google's Credential Manager documentation](https://developer.android.com/training/sign-in/credential-manager).

```go lines expandable theme={null}
// Generate a nonce for token replay protection
val randomNonce = UUID.randomUUID().toString()

// Prepare a Sign in request
val googleIdOption: GetGoogleIdOption = GetGoogleIdOption.Builder()
    // This must match the Client ID Configured in the auth0 dashboard
    .setServerClientId(
        getString(R.string.com_google_client_id)
    )
	.setNonce(randomNonce)
    .build()

val request: GetCredentialRequest = GetCredentialRequest.Builder()
    .addCredentialOption(googleIdOption)
    .build()

// To Prompt
val credMan = CredentialManager.create(this@MainActivity.baseContext);
val result = credMan.getCredential(
    request = request,
    context = this@MainActivity.baseContext,
)

// Handle outcome 
val creds = result.credential

when (creds) {
    is CustomCredential -> {
        if (creds.type ==
                    GoogleIdTokenCredential.TYPE_GOOGLE_ID_TOKEN_CREDENTIAL
            ) {
                try {
                    val googleCredentials = GoogleIdTokenCredential
                            .createFrom(creds.data)
// Rest of the code
```

## Additional authentication scenarios

While the current Google implementation does not offer clear guidance for enterprise federation and additional <Tooltip tip="Multi-factor authentication (MFA): User authentication process that uses a factor in addition to username and password such as a code via SMS." cta="View Glossary" href="/docs/glossary?term=multi-factor+authentication">multi-factor authentication</Tooltip> (MFA) challenges, you can accommodate these capabilities by transitioning to the web experience.

### Enterprise federation

Auth0 supports enterprise federation, which allows you to connect external [enterprise identity providers](/docs/authenticate/identity-providers/enterprise-identity-providers) (such as Okta Workforce, ADFS, or other OIDC-compatible systems) to your Auth0 tenant so that users can then authenticate with their existing corporate credentials.

If you require the use of enterprise federation, redirecting the user to the web-based flow is recommended, instead of relying on the `id_token` as demonstrated in previous examples.

To do so, decode the Google <Tooltip tip="JSON Web Token (JWT): Standard ID Token format (and often Access Token format) used to represent claims securely between two parties." cta="View Glossary" href="/docs/glossary?term=JWT">JWT</Tooltip> token and pass the `email` provided in the <Tooltip tip="JSON Web Token (JWT): Standard ID Token format (and often Access Token format) used to represent claims securely between two parties." cta="View Glossary" href="/docs/glossary?term=ID+token">ID token</Tooltip> as a `login_hint`. This prevents the end user from having to re-enter their email address in the web flow.

```go lines theme={null}
if (error.isAccessDenied && reason == "Enterprise Domain") {
WebAuthProvider.login(account)
	.withParameters(mapOf("login_hint" to email))
	.start(...)
}
```

### MFA considerations during token exchange

Auth0 returns an error to the application during token exchange when the Google OAuth connection policy requires multi-factor authentication.  This error is included in the response to the application.

When the above error occurs, your application can use WebAuth with the enriched context available in the Google `id_token`. In this scenario, the end user will only see the MFA screen.

```go lines theme={null}
if (error.isMultifactorRequired) {
WebAuthProvider.login(account)
	.withParameters(mapOf(
"login_hint" to email,
"connection" to "google-oauth-2"
))
	.start(...)
}
```
