Google login authentication with Firebase in Android (2020)
Tags: android, java, googlecloud
Published: 2020-07-05 09:26:39


![Alt Text](https://miro.medium.com/max/960/1*Q12oZ5CgItDK9kGr9Cw4Hw.gif)



Add the following dependencies in your build.gradle

```
implementation 'com.google.firebase:firebase-auth:19.3.1'  
implementation 'com.google.android.gms:play-services-auth:18.0.0'
```

![Alt Text](https://miro.medium.com/max/1400/1*9tlt6_Ta7JlDJIWX8nHw_Q.png)

Before starting, I am assuming that you already connected your Android app with firebase. In this case, I already connected week12lab with firebase

![Alt Text](https://miro.medium.com/max/1400/1*WtQocO3Fg-ok5_jThm8e3A.png)

Afterwards, press the Android option and create a new app

![Alt Text](https://miro.medium.com/max/1400/1*_CBaiQs7Pe0MDuWjtd9cvQ.png)

The Android package name can be found in the build.gradle file under the applicationId name. Additionally we will have to create a SHA-1 certificate for debug signing

In order to generate the SHA-1 key type the following command in your terminal

_keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android_

![Alt Text](https://miro.medium.com/max/1400/1*hJQuvXWId0h557GdY-QLSQ.png)


Result of the command. I hid my SHA1 certificate fingerprints.

![Alt Text](https://miro.medium.com/max/1400/1*iz416V5MKhlcfcBuVZZnKQ.png)

Add the google-services.json file to your app folder

![Alt Text](https://miro.medium.com/max/1400/1*RYZ0vXViiACfno_6xjjdAA.png)

Outline
=======

A detailed explanation can be found in Google’s [official documentation](https://developers.google.com/identity/sign-in/android/sign-in). This tutorial is simply made to explain each step as concisely as possible.

1.  Configure Google Sign-in and GoogleSignInClient object
2.  Check for existing signed-in use
3.  Use Firebase Auth
4.  Add What will happen if valid user logs in
5.  Add a logout button
6.  Play with user’s data
7.  Update manifest

1 | Configure Google Sign-in and the GoogleSignInClient object
==============================================================

The following makes a sign in request to google

```
// Configure Google Sign In  
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT\_SIGN\_IN)  
        .requestIdToken(getString(R.string.default\_web\_client\_id))  
        .requestEmail()  
        .build();
```

![Alt Text](https://miro.medium.com/max/1400/1*1NWm9C0nd46EamE_iJlYFw.png)

Afterwards in onCreate we will need to add a Google sign in client

```
// Build a GoogleSignInClient with the options specified by gso.  
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
```

![Alt Text](https://miro.medium.com/max/1400/1*HBIGpHk2FEgSeSAGIcLgvA.png)


Line 15 and 27, show how we added a new GoogleSignInClient and instantiated it in the onCreate method.

2 | Create XML login button and Signin Method
=============================================

**Create Login Button**

Create a new XML class called login.xml and add the Google sign in button.

![Alt Text](https://miro.medium.com/max/1400/1*n5G0A8OFabUtIFPKm2ebbA.png)

**Create a Sign In Method**

We then need to make a sign in intent to Google. We will have to make a new method in the LoginActivity class.

```
private void signIn() {  
    Intent signInIntent = mGoogleSignInClient.getSignInIntent();  
    startActivityForResult(signInIntent, RC\_SIGN\_IN);  
}
```

![Alt Text](https://miro.medium.com/max/1400/1*hZWSyMDNhdrGY59bJ3FjVQ.png)

RC\_SIGN\_IN can be any number. In this case, I assigned 1.

**Create a new listener to use Sign In method**

![Alt Text](https://miro.medium.com/max/1400/1*HnGTzWZSzrMnrhuD9QcaiA.png)

Create a new onclicklistener that makes use of the new signin() method we just created.

**Find the button and set the onClickListener**

![Alt Text](https://miro.medium.com/max/1400/1*iYYYX4hoyFTz80p61tHTtA.png)

Find the button that we create in our XML and assign the handleGoogleLogin listener to it.

3 | Use Firebase Auth
=====================

Now that we have made the intent, we can now check if the google account is a valid account.

**Add onActivityResult**

```
  
@Override  
public void onActivityResult(int requestCode, int resultCode, Intent data) {  
    super.onActivityResult(requestCode, resultCode, data);  
  
  
    // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);  
    if (requestCode == _RC\_SIGN\_IN_) {  
        Task<GoogleSignInAccount> task = GoogleSignIn._getSignedInAccountFromIntent_(data);  
        try {  
            // Google Sign In was successful, authenticate with Firebase  
            GoogleSignInAccount account = task.getResult(ApiException.class);  
            firebaseAuthWithGoogle(account);  
        } catch (ApiException e) {  
            // Google Sign In failed, update UI appropriately  
            // ...  
            Toast._makeText_(this, e.getMessage(), Toast._LENGTH\_SHORT_).show();  
        }  
    }  
}
```

**Add firebaseAuthWithGoogle(String idToken)**

The credentials below will be the credential of the user logging in. If it is a success then we allow the user to sign in.

```
private void firebaseAuthWithGoogle(GoogleSignInAccount account) {  
    AuthCredential credential = GoogleAuthProvider._getCredential_(account.getIdToken(), null);  
  
    mAuth.signInWithCredential(credential)  
            .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  
                        FirebaseUser user = mAuth.getCurrentUser();  
                        Intent intent = new Intent(getApplicationContext(), MainActivity.class);  
                        startActivity(intent);  
  
                    } else {  
                        // If sign in fails, display a message to the user.  
                        Toast._makeText_(getApplicationContext(), "Sorry authentication failed ", Toast._LENGTH\_SHORT_).show();  
  
                    }  
                }  
            });  
}
```

Instantiate the FirebaseAuth in onCreate()

```
mAuth = FirebaseAuth.getInstance();
```

4 | Add What will happen if valid user logs in
==============================================

On the onStart() lifecycle method add the following code in order to check if the current user is already signed in.

```
protected void onStart() {  
  
    super.onStart();  
    FirebaseUser currentUser = mAuth.getCurrentUser();  
    if(currentUser!=null){  
        Intent intent = new Intent(getApplicationContext(),MainActivity.class);  
        startActivity(intent);  
    }  
}
```

5 | Add a logout button
=======================

In my case, I have already had a drawer navigation layout. As such, I made a new id so that I can find the logout id and use it. However, whether or not you use a drawer navigation option to do this, the process will still be the same.

![Alt Text](https://miro.medium.com/max/1248/1*qfMUOpzc8BXkTxaBMrwCrw.png)

The important part of this code is the logout id

Create a handleLogout method. This can also be rewritten as a onClickListener incase you are using buttons

![Alt Text](https://miro.medium.com/max/1400/1*-NKrqKRfrx6mNr4d3eeY5g.png)

The following invokes handleLogout when the logout case is chosen

![Alt Text](https://miro.medium.com/max/800/1*Emb3acchvMdeai5eQkLNFQ.png)

6 | Play with user’s data
=========================

Now that a user has logged in, We can find some data about them to make the app more personalised to them. One way we can do this is by creating a toast if they logged back in the app. We can do this by adding the following in the MainActivity’s onCreate

```
//Google sign  
GoogleSignInAccount signInAccount= GoogleSignIn._getLastSignedInAccount_(this);  
if(signInAccount!=null){  
    Toast.makeText(this, "Welcome back "signInAccount.getDisplayName() , Toast._LENGTH\_SHORT_).show();  
}
```

7 | Update manifest
===================

Make sure both LoginActivity and MainActivity are in the manifest

![Alt Text](https://miro.medium.com/max/1400/1*4wlceU9LC6-ToS6uOR69xA.png)
8 | Test
========

![Alt Text](https://miro.medium.com/max/548/1*i7ZCsL51Oo5rFDOuXz1Jjw.gif)