Ionic Google Authentication using Firebase

First Published: 2 March 2017
Updated on: 1 November 2018

Google and Facebook are the most common ways to use social login in your apps, a while back we covered Facebook login using Firebase, and today it’s time for Ionic Google authentication.

We’re going to create a Google login for our ionic apps, and then extract some information from the auth object (profile picture, name, and email) to show on our home page.

We’re going to break down the process into 3 steps:

  • Step #1: Get your credentials from Google.
  • Step #2: Install the Google native plugin.
  • Step #3: Log In using Google and Firebase.

To follow along with this tutorial, I’m going to assume you already know how to create a brand new Ionic app and initialize it with Firebase. If you don’t know yet, you can read this post first.

Step #1: Get your credentials from Google

The first thing we need to do is set up everything we’re going to need from Google to get our app working, we need to get:

  • A REVERSED_CLIENT_ID from the google developers console.
  • Enable Google sign-in inside the developer console.
  • Pass the credentials to install the plugin.

To start generating the credentials and enabling everything we’re going to create both the iOS and the Android app in our developer console, let’s start with the iOS one, go to this link and create the iOS app.

It’s going to ask you to create a new app or to select one from the drop-down menu, you can select the Firebase app you have already created.

iOS Setup

After you select the app it will ask you for an iOS Bundle ID, to get it, go into your app’s config.xml file and copy the package id you’re using, it’s the one that looks like com.ionicframework.something (by the way, I strongly suggest you change it to something more custom to your project).

Then it’s going to ask you to enable Google Sign-In, just click to generate and then it will show a big button that says Generate Configuration Files, go ahead and click it, it will let you download your GoogleService-Info.plist file, which is a config file for iOS.

Enable Google SignIn

After we’re done there, we’re going to do the exact same thing but for Android, you can create (or link) the new app here.

When you link the account it’s going to ask you to enable Google SignIn, but this process is a bit (actually a lot) different that what we just did with iOS, you need to generate an Android Signing Certificate SHA-1 and pass it to the form.

Google Login Enable

Getting the SHA-1 signing certificate requires a bit of command line work, I’m going to do my best to make it as simple as possible.

There are 2 certificate signings you need, we’re going to do the first one right now, and you’re going to do the second one on your own if you are going to publish your app to Google Play (I’ll show you how you’ll do it).

The first one is the debug certificate, we’re going to get it to make sure everything works when we’re developing the app, since we’re using an un-signed apk to run it in our android devices.

To get it, you’re going to open your terminal and type:

keytool -exportcert -list -v -alias androiddebugkey -keystore ~/.android/debug.keystore

Where ~/.android/debug.keystore is where 99,99% of the time you’ll find it, if not, check your android SDK install to see where it is.

When you run that command, it’s going to ask you for the keystore password, the default one is android.

Sign SHA Certificate

From the output copy the SHA1 certificate fingerprints and paste them into the Google Developers form, then click on Enable Google Sign-In, and that’s it, you can click on generate config files, but we’re not going to need them.

Now we need to install the native plugin that will let us interact with Google login.

Step #2: Install the Cordova Plugin

We’re going to use the cordova-plugin-googleplus created by Eddy Verbruggen through the Ionic Native wrapper.

To install the plugin, open your terminal and type this:

cordova plugin add cordova-plugin-googleplus --save --variable REVERSED_CLIENT_ID=myreversedclientid

npm install --save @ionic-native/google-plus

Where we’re going to replace myreversedclientid with the reversed version of the client id.

Side-note here, I wasted about 40 minutes with a cryptic error because I used the wrong ID here =/

You can find your REVERSED_CLIENT_ID inside the GoogleService-Info.plist file :P

And after you install the plugin run

cordova prepare

Then make sure to inject the GooglePlus package as a provider in app.module.ts

import { SplashScreen } from '@ionic-native/splash-screen';
import { StatusBar } from '@ionic-native/status-bar';
import { GooglePlus } from '@ionic-native/google-plus';

@NgModule({
  ...,
  providers: [
    {provide: ErrorHandler, useClass: IonicErrorHandler},
    SplashScreen,
    StatusBar,
    GooglePlus
  ]
})
export class AppModule {}

And that’s it, everything should be ready to use right now, in the next part we’ll move to coding.

Step #3: Ionic Google Login with Firebase

Now we can get our functionality working, we’re going to divide it in 2 parts, the first thing we’ll do is to create our view, so go into home.html and make it look like this:

<ion-toolbar>
  <ion-buttons slot="start">
    <ion-back-button></ion-back-button>
  </ion-buttons>
  <ion-title></ion-title>
</ion-toolbar>

<ion-content padding>
  <ion-button
    expand="block"
    color="danger"
    (click)="loginUser()"
    \*ngIf="!userProfile"
  >
    <ion-icon name="logo-googleplus"></ion-icon>
    Login with Google
  </ion-button>

  <ion-item \*ngIf="userProfile">
    <ion-label>
      <ion-avatar slot="left">
        <img [src]="userProfile.photoURL" />
      </ion-avatar>
      ## {{ userProfile.displayName }}
      <h3>{{ userProfile.email }}</h3>
    </ion-label>
  </ion-item>
</ion-content>

Nothing we haven’t seen before, we have a

<ion-button
  expand="block"
  color="danger"
  (click)="loginUser()"
  *ngIf="!userProfile"
>
  <ion-icon name="logo-googleplus"></ion-icon>
  Login with Google
</ion-button>

That only shows up if there’s no user and when you click on it you call the loginUser() function.

And we have an

<ion-item *ngIf="userProfile">
  <ion-label>
    <ion-avatar slot="left">
      <img [src]="userProfile.photoURL" />
    </ion-avatar>
    ## {{ userProfile.displayName }}
    <h3>{{ userProfile.email }}</h3>
  </ion-label>
</ion-item>

That is showing the picture, email, and name of the user.

It should look a bit like this:

Google Login Ionic

After that let’s move to the home.ts file and start working on our code, the first thing we’re going to do is to import everything we need here:

import { Component } from '@angular/core';
import { GooglePlus } from '@ionic-native/google-plus';
import firebase from 'firebase';

We’re importing GooglePlus from Ionic native to handle the native login flow, and we’re importing Firebase because we’re going to be creating a Firebase account for our users with the credentials from the Google login.

Next, to avoid any errors if you’re running the app now, let’s declare the userProfile variable we are using in the HTML and to create the authentication observer to handle that variable’s value, we also need to inject GooglePlus into the constructor.

userProfile: any = null;

constructor(public navCtrl: NavController, private googlePlus: GooglePlus) {
  firebase.auth().onAuthStateChanged( user => {
    if (user){
      this.userProfile = user;
    } else {
      this.userProfile = null;
    }
  });
}

That way we’re controlling what we show on the HTML, if there’s a logged in user then we’re assigning her information to the userProfile variable, and if there isn’t we’re leaving it as null.

Now it’s time to create our login function, the first thing we want to do is to log our user in using Google, for this, we’re going to use the login() function from the GooglePlus package

loginUser(): void {
  this.googlePlus.login({
    'webClientId': '<Your web client ID>',
    'offline': true
  }).then( res => console.log(res))
    .catch(err => console.error(err));
}

The .login() function receives and object with some options, you can read all about it in the plugin official docs.

But for this example, we’re skipping most of them, because the defaults are enough, we’re passing offline: true and our webClientId to get back an idToken we can pass to Firebase.

If you don’t send these, then your app will work with iOS but for Android it won’t return the idToken.

If you don’t know where to get the webClientId, you get it from the API Manager for the Google Developers Console, same as the REVERSED CLIENT_ID (_it’s the same one, shhhhhhh*).

Google Credential Manager

Once you get that working, you get the login process working, and it will prompt the user to give your app access to his google sign-in.

Google Login Page

Right there we have Google login implemented, and you can use it for whatever you want, even using that token to sign in with a node app or any other backend you choose.

Since this tutorial is about Firebase, it’s time now to use those credentials we just got from Google to create a Firebase account:

loginUser(): void {
  this.googlePlus.login({
    'webClientId': '<Your web client ID>',
    'offline': true
  }).then( res => {
    firebase.auth().signInWithCredential(firebase.auth.GoogleAuthProvider.credential(res.idToken))
      .then( success => {
        console.log("Firebase success: " + JSON.stringify(success));
      })
      .catch( error => console.log("Firebase failure: " + JSON.stringify(error)));
    }).catch(err => console.error("Error: ", err));
}

Pay attention to this block of code here:

firebase
  .auth()
  .signInWithCredential(
    firebase.auth.GoogleAuthProvider.credential(res.idToken)
  );

We’re calling Firebase’s signInWithCredential() method and we’re passing it a credential object, we’re getting the credential object here:

firebase.auth.GoogleAuthProvider.credential(res.idToken);

And that’s it, you should have a fully working Google login for Ionic and Firebase, once your user logs in you can show her whatever you want:

Google Login Page Success

Keep in mind that if you want to publish your app to Google Play you’ll need to add your keystore fingerprints for release, to get those, instead of using the debug keystore

keytool -exportcert -list -v \
-alias androiddebugkey -keystore ~/.android/debug.keystore

You need to use the one you created for uploading android apps:

keytool -exportcert -list -v \
-alias androiddebugkey -keystore <path to keystore here>

And remember the password you chose for it, if you haven’t created one, then this is the ionic tutorial I follow to publish every single app.

Next Steps

If you have any questions don’t forget you can always leave a comment below.

If you want to take a deeper dive on Ionic + Firestore you should go through my FREE course: Build your first Firestore powered Ionic app.