Firebase Google Plus Authentication In Android

Firebase Google Plus Authentication In Android


As discussed in our previous posts, we have learned how to perform email authentication and phone number authentication with Firebase in Android. In this article, we will see how to perform Google Plus authentication in Android.
You can find my previous posts at the following links.
  1. Firebase Email Authentication - Part One
  2. Firebase Email Authentication - Part Two
  3. Firebase Phone Authentication

Firebase G-Plus Authentication

Firebase helps developers manage Google Plus Authentication in an easy way. Before starting, we have to add or enable Google Plus Authentication in Firebase console.

Firebase Setup

Before we start coding, we have to set up Firebase for Android and enable phone authentication. If you are new to Firebase, the following link will be useful to learn the method of setting up the project in Firebase.
After setting up, open the Authentication Sign-in method and enable the phone authentication method as shown in the following figure.
Firebase Google Plus Authentication In Android
You should add SHA Fingerprint in your application. The following terminal will be used to get the SHA Fingerprint with the Command Prompt in Windows in the debug mode.
keytool -list -v -keystore "%USERPROFILE%\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android
I have split this part into 3 steps as in the following.
  • Step 1- Creating a new project with an empty activity.
  • Step 2- Setting up the Firebase Library.
  • Step 3- Implementation of Firebase Google Plus Authentication.
Step 1 - Creating a new project with Android Studio
  1. Open Android Studio and select "Create New Project".
  2. Name the project as you wish and select your activity template.
    Firebase Google Plus Authentication In Android
  3. Click the Finish button to create a new project in Android Studio.
Step 2 - Setting up the Firebase Library
In this part, we will see how to set up the library for the project.
  1. Open your project level build.gradle file and add the following lines in dependencies.
    1.  {  
    2.     …  
    3.     classpath ''  
    4.               …  
    5. }  
  1. Then, add the following lines in allprojects in the project level build.gradle file.
    1. allprojects {  
    2.     repositories {  
    3.         google()  
    4.         jcenter()  
    5.         maven {  
    6.             url ""  
    7.         }  
    8.     }  
    9. }  
  1. Then, add the following lines in app level build.gradle file to apply Google Services to your project.
    1. dependencies {  
    2.     ...  
    3.     implementation ''  
    4.     implementation ''  
    5.     implementation 'com.squareup.picasso:picasso:2.71828'  
    6. }  
  1. Then, click Sync Now to set up your project.
Step 3 - Implementation of Firebase Google Plus Authentication
Initialize the Google Sign-in Client with Google Sign-in options and Firebase Auth Client, as shown in the below snippet.
  1. //first we initialized the Firebase Auth object  
  2. FirebaseAuth mAuth = FirebaseAuth.getInstance();  
  4. //Then we need a GoogleSignInOptions object  
  5. //And we need to build it as below  
  6. GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)  
  7.         .requestIdToken(getString(R.string.default_web_client_id))  
  8.         .requestEmail()  
  9.         .build();  
  11. //Then we will get the GoogleSignInClient object from GoogleSignIn class  
  12. GoogleSignInClient mGoogleSignInClient = GoogleSignIn.getClient(this, gso);  
You must pass your server's client ID to the requestIdToken method. To find the OAuth 2.0 client ID, open the Credentials page in the API Console. The web application type client ID is your backend server's OAuth 2.0 Client ID.
Then, add the following code to initiate Google Sign-in.
  1. //getting the google signin intent  
  2. Intent signInIntent = mGoogleSignInClient.getSignInIntent();  
  3. //starting the activity for result  
  4. startActivityForResult(signInIntent, RC_SIGN_IN);  
Add the onActivityResult, as shown below.
  1. @Override  
  2. public void onActivityResult(int requestCode, int resultCode, Intent data) {  
  3.     super.onActivityResult(requestCode, resultCode, data);  
  5.     //if the requestCode is the Google Sign In code that we defined at starting  
  6.     if (requestCode == RC_SIGN_IN) {  
  8.         //Getting the GoogleSignIn Task  
  9.         Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);  
  10.         try {  
  11.             //Google Sign In was successful, authenticate with Firebase  
  12.             GoogleSignInAccount account = task.getResult(ApiException.class);  
  13.             //authenticating with firebase  
  14.             firebaseAuthWithGoogle(account);  
  15.         } catch (ApiException e) {  
  16.             Log.v("API Exception", e.toString());  
  17.             Toast.makeText(LoginActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();  
  18.         }  
  19.     }  
  20. }  
After a user successfully signs in, get an ID token from the GoogleSignInAccount object, exchange it for a Firebase credential, and authenticate with Firebase using the Firebase credentials.
  1. private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {  
  2.     Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());  
  4.     //getting the auth credential  
  5.     AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);  
  7.     //Now using firebase we are signing in the user here  
  8.     mAuth.signInWithCredential(credential)  
  9.                             .addOnCompleteListener(thisnew OnCompleteListener<AuthResult>() {  
  10.         @Override  
  11.         public void onComplete(@NonNull Task<AuthResult> task) {  
  12.             if (task.isSuccessful()) {  
  13.                 if (mAuth.getCurrentUser() != null) {  
  14.                     startActivity(new Intent(LoginActivity.this, MainActivity.class));  
  15.                     finish();  
  16.                 }  
  17.             } else {  
  18.                 // If sign-in fails, display a message to the user.  
  19.                 Log.w(TAG, "signInWithCredential:failure", task.getException());  
  20.                 Toast.makeText(LoginActivity.this"Authentication failed.",  
  21.                     Toast.LENGTH_SHORT).show();  
  22.             }  
  23.         }  
  24.     });  
  25. }  
If the user is authenticated with Google Plus Sign-In successfully, then login screen is redirected to the next activity.
To retrieve user details like name, profile picture, mail id through Firebase, use the following snippets.
  1. FirebaseAuth mAuth = FirebaseAuth.getInstance();  
  2. FirebaseUser user = mAuth.getCurrentUser();  
  4. assert user != null;  
  5. textName.setText(user.getDisplayName());  
  6. textEmail.setText(user.getEmail());  
  8. Picasso.get().load(user.getPhotoUrl()).into(imageView);  
Here, I have used Picasso Image Loading Library to load images. To learn more, click here.
Download Code
You can download the full source code of the article on GitHub. If you like this article, do star the repo in GitHub.