Authenticate with Google on Android

You can let your users authenticate with Firebase using their Google Accounts.

Before you begin

  1. If you haven't already, add Firebase to your Android project.

  2. In your module (app-level) Gradle file (usually <project>/<app-module>/build.gradle.kts or <project>/<app-module>/build.gradle), add the dependency for the Firebase Authentication library for Android. We recommend using the Firebase Android BoM to control library versioning.

    Also, as part of setting up Firebase Authentication, you need to add the Google Play services SDK to your app.

    dependencies {
        // Import the BoM for the Firebase platform
        implementation(platform("com.google.firebase:firebase-bom:33.5.1"))
    
        // Add the dependency for the Firebase Authentication library
        // When using the BoM, you don't specify versions in Firebase library dependencies
        implementation("com.google.firebase:firebase-auth")
    // Also add the dependency for the Google Play services library and specify its version implementation("com.google.android.gms:play-services-auth:21.2.0")
    }

    By using the Firebase Android BoM, your app will always use compatible versions of Firebase Android libraries.

    (Alternative)  Add Firebase library dependencies without using the BoM

    If you choose not to use the Firebase BoM, you must specify each Firebase library version in its dependency line.

    Note that if you use multiple Firebase libraries in your app, we strongly recommend using the BoM to manage library versions, which ensures that all versions are compatible.

    dependencies {
        // Add the dependency for the Firebase Authentication library
        // When NOT using the BoM, you must specify versions in Firebase library dependencies
        implementation("com.google.firebase:firebase-auth:23.1.0")
    // Also add the dependency for the Google Play services library and specify its version implementation("com.google.android.gms:play-services-auth:21.2.0")
    }
    Looking for a Kotlin-specific library module? Starting in October 2023 (Firebase BoM 32.5.0), both Kotlin and Java developers can depend on the main library module (for details, see the FAQ about this initiative).

  3. If you haven't yet specified your app's SHA fingerprint, do so from the Settings page of the Firebase console. Refer to Authenticating Your Client for details on how to get your app's SHA fingerprint.

  4. Enable Google as a sign-in method in the Firebase console:
    1. In the Firebase console, open the Auth section.
    2. On the Sign in method tab, enable the Google sign-in method and click Save.
  5. When prompted in the console, download the updated Firebase config file (google-services.json), which now contains the OAuth client information required for Google sign-in.

  6. Move this updated config file into your Android Studio project, replacing the now-outdated corresponding config file. (See Add Firebase to your Android project.)

Authenticate with Firebase

  1. Integrate Google One Tap sign-in into your app by following the steps on the Sign users in with their saved credentials page. When you configure the BeginSignInRequest object, call setGoogleIdTokenRequestOptions:

    Kotlin+KTX

    signInRequest = BeginSignInRequest.builder()
                .setGoogleIdTokenRequestOptions(
                    BeginSignInRequest.GoogleIdTokenRequestOptions.builder()
                        .setSupported(true)
                        // Your server's client ID, not your Android client ID.
                        .setServerClientId(getString(R.string.your_web_client_id))
                        // Only show accounts previously used to sign in.
                        .setFilterByAuthorizedAccounts(true)
                        .build())
                .build()

    Java

    signInRequest = BeginSignInRequest.builder()
        .setGoogleIdTokenRequestOptions(GoogleIdTokenRequestOptions.builder()
                .setSupported(true)
                // Your server's client ID, not your Android client ID.
                .setServerClientId(getString(R.string.default_web_client_id))
                // Only show accounts previously used to sign in.
                .setFilterByAuthorizedAccounts(true)
                .build())
        .build();
        
    You must pass your "server" client ID to the setGoogleIdTokenRequestOptions method. To find the OAuth 2.0 client ID:
    1. Open the Credentials page in the Google Cloud console.
    2. The Web application type client ID is your backend server's OAuth 2.0 client ID.
    After you integrate Google Sign-In, your sign-in activity has code similar to the following:

    Kotlin+KTX

    class YourActivity : AppCompatActivity() {
    
        // ...
        private val REQ_ONE_TAP = 2  // Can be any integer unique to the Activity
        private var showOneTapUI = true
        // ...
    
        override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
            super.onActivityResult(requestCode, resultCode, data)
    
            when (requestCode) {
                 REQ_ONE_TAP -> {
                    try {
                        val credential = oneTapClient.getSignInCredentialFromIntent(data)
                        val idToken = credential.googleIdToken
                        when {
                            idToken != null -> {
                                // Got an ID token from Google. Use it to authenticate
                                // with Firebase.
                                Log.d(TAG, "Got ID token.")
                            }
                            else -> {
                                // Shouldn't happen.
                                Log.d(TAG, "No ID token!")
                            }
                        }
                    } catch (e: ApiException) {
                        // ...
                }
            }
        }
        // ...
    }

    Java

    public class YourActivity extends AppCompatActivity {
    
      // ...
      private static final int REQ_ONE_TAP = 2;  // Can be any integer unique to the Activity.
      private boolean showOneTapUI = true;
      // ...
    
      @Override
      protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
          super.onActivityResult(requestCode, resultCode, data);
    
          switch (requestCode) {
              case REQ_ONE_TAP:
                  try {
                      SignInCredential credential = oneTapClient.getSignInCredentialFromIntent(data);
                      String idToken = credential.getGoogleIdToken();
                      if (idToken !=  null) {
                          // Got an ID token from Google. Use it to authenticate
                          // with Firebase.
                          Log.d(TAG, "Got ID token.");
                      }
                  } catch (ApiException e) {
                      // ...
                  }
                  break;
          }
      }
    }
  2. In your sign-in activity's onCreate method, get the shared instance of the FirebaseAuth object:

    Kotlin+KTX

    private lateinit var auth: FirebaseAuth
    // ...
    // Initialize Firebase Auth
    auth = Firebase.auth

    Java

    private FirebaseAuth mAuth;
    // ...
    // Initialize Firebase Auth
    mAuth = FirebaseAuth.getInstance();
  3. When initializing your Activity, check to see if the user is currently signed in:

    Kotlin+KTX

    override fun onStart() {
        super.onStart()
        // Check if user is signed in (non-null) and update UI accordingly.
        val currentUser = auth.currentUser
        updateUI(currentUser)
    }

    Java

    @Override
    public void onStart() {
        super.onStart();
        // Check if user is signed in (non-null) and update UI accordingly.
        FirebaseUser currentUser = mAuth.getCurrentUser();
        updateUI(currentUser);
    }
  4. In your onActivityResult() handler (see step 1), get the user's Google ID token, exchange it for a Firebase credential, and authenticate with Firebase using the Firebase credential:

    Kotlin+KTX

    val googleCredential = oneTapClient.getSignInCredentialFromIntent(data)
    val idToken = googleCredential.googleIdToken
    when {
        idToken != null -> {
            // Got an ID token from Google. Use it to authenticate
            // with Firebase.
            val firebaseCredential = GoogleAuthProvider.getCredential(idToken, null)
            auth.signInWithCredential(firebaseCredential)
                    .addOnCompleteListener(this) { task ->
                        if (task.isSuccessful) {
                            // Sign in success, update UI with the signed-in user's information
                            Log.d(TAG, "signInWithCredential:success")
                            val user = auth.currentUser
                            updateUI(user)
                        } else {
                            // If sign in fails, display a message to the user.
                            Log.w(TAG, "signInWithCredential:failure", task.exception)
                            updateUI(null)
                        }
                    }
        }
        else -> {
            // Shouldn't happen.
            Log.d(TAG, "No ID token!")
        }
    }

    Java

    SignInCredential googleCredential = oneTapClient.getSignInCredentialFromIntent(data);
    String idToken = googleCredential.getGoogleIdToken();
    if (idToken !=  null) {
        // Got an ID token from Google. Use it to authenticate
        // with Firebase.
        AuthCredential firebaseCredential = GoogleAuthProvider.getCredential(idToken, null);
        mAuth.signInWithCredential(firebaseCredential)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            // Sign in success, update UI with the signed-in user's information
                            Log.d(TAG, "signInWithCredential:success");
                            FirebaseUser user = mAuth.getCurrentUser();
                            updateUI(user);
                        } else {
                            // If sign in fails, display a message to the user.
                            Log.w(TAG, "signInWithCredential:failure", task.getException());
                            updateUI(null);
                        }
                    }
                });
    }
    If the call to signInWithCredential succeeds you can use the getCurrentUser method to get the user's account data.

Next steps

After a user signs in for the first time, a new user account is created and linked to the credentials—that is, the user name and password, phone number, or auth provider information—the user signed in with. This new account is stored as part of your Firebase project, and can be used to identify a user across every app in your project, regardless of how the user signs in.

  • In your apps, you can get the user's basic profile information from the FirebaseUser object. See Manage Users.

  • In your Firebase Realtime Database and Cloud Storage Security Rules, you can get the signed-in user's unique user ID from the auth variable, and use it to control what data a user can access.

You can allow users to sign in to your app using multiple authentication providers by linking auth provider credentials to an existing user account.

To sign out a user, call signOut:

Kotlin+KTX

Firebase.auth.signOut()

Java

FirebaseAuth.getInstance().signOut();