Introduction
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.
- Firebase Email Authentication - Part One
- Firebase Email Authentication - Part Two
- 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.
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
Steps
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
- Open Android Studio and select "Create New Project".
- Name the project as you wish and select your activity template.
- 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.
- Open your project level build.gradle file and add the following lines in dependencies.
- {
- …
- classpath 'com.google.gms:google-services:4.0.1'
- …
- }
- Then, add the following lines in allprojects in the project level build.gradle file.
- allprojects {
- repositories {
- google()
- jcenter()
- maven {
- url "https://maven.google.com"
- }
- }
- }
- Then, add the following lines in app level build.gradle file to apply Google Services to your project.
- dependencies {
- ...
- implementation 'com.google.firebase:firebase-auth:16.0.2'
- implementation 'com.google.android.gms:play-services-auth:15.0.1'
- implementation 'com.squareup.picasso:picasso:2.71828'
- }
- 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.
-
- FirebaseAuth mAuth = FirebaseAuth.getInstance();
-
-
-
- GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
- .requestIdToken(getString(R.string.default_web_client_id))
- .requestEmail()
- .build();
-
-
- 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.
-
- Intent signInIntent = mGoogleSignInClient.getSignInIntent();
-
- startActivityForResult(signInIntent, RC_SIGN_IN);
Add the onActivityResult, as shown below.
- @Override
- public void onActivityResult(int requestCode, int resultCode, Intent data) {
- super.onActivityResult(requestCode, resultCode, data);
-
-
- if (requestCode == RC_SIGN_IN) {
-
-
- Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
- try {
-
- GoogleSignInAccount account = task.getResult(ApiException.class);
-
- firebaseAuthWithGoogle(account);
- } catch (ApiException e) {
- Log.v("API Exception", e.toString());
- Toast.makeText(LoginActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
- }
- }
- }
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.
- private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
- Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());
-
-
- AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
-
-
- mAuth.signInWithCredential(credential)
- .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
- @Override
- public void onComplete(@NonNull Task<AuthResult> task) {
- if (task.isSuccessful()) {
- if (mAuth.getCurrentUser() != null) {
- startActivity(new Intent(LoginActivity.this, MainActivity.class));
- finish();
- }
- } else {
-
- Log.w(TAG, "signInWithCredential:failure", task.getException());
- Toast.makeText(LoginActivity.this, "Authentication failed.",
- Toast.LENGTH_SHORT).show();
- }
- }
- });
- }
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.
- FirebaseAuth mAuth = FirebaseAuth.getInstance();
- FirebaseUser user = mAuth.getCurrentUser();
-
- assert user != null;
- textName.setText(user.getDisplayName());
- textEmail.setText(user.getEmail());
-
- 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.