Firebase Google Authentication using ionic
Firebase Google Authentication using ionic
ionic-firebase-google-login

This article, we’ll learn how to implement firebase google authentication using Ionic. Before we starting we need to create google reverse client id for adding plugin. please refer https://codesundar.com/tutorials/create-reverse-client-id-for-google-login/ for detailed instructions

Let’s create new project & Add required dependencies

ionic start firebasegoogleauth blank
cd firebasegoogleauth

ionic cordova platform add android
ionic cordova platform add ios

ionic cordova plugin add cordova-plugin-googleplus --save --variable REVERSED_CLIENT_ID=myreversedclientid
npm install --save @ionic-native/google-plus

npm install --save firebase

Working with app.component.ts & app.module.ts

After adding all plugins and packages, we need to initiate our firebase inside app.component.ts

firebase.initializeApp({
      apiKey: "xxx",
      authDomain: "xxx",
      databaseURL: "xxx",
      projectId: "xxx",
      storageBucket: "xxx",
      messagingSenderId: "xxx"
    });

We need to declare plugin inside app.module.ts

import { GooglePlus } from '@ionic-native/google-plus';
.
.
.
.
providers: [
    StatusBar,
    SplashScreen,
    GooglePlus,
    {provide: ErrorHandler, useClass: IonicErrorHandler}
  ]

Working with home.html

Let’s create a new button for login with google. when the user click that button, we need to take two decision.

if app is running on browser, we need to call this code for a signup purpose

if (this.platform.is('core')) {
  firebase.auth().signInWithPopup(new firebase.auth.GoogleAuthProvider()).then(gpRes => {
    this.displayToast('Login Success')
    this.userData = gpRes.additionalUserInfo.profile;
  }).catch(err => this.displayToast(err));
}

If app is running on device, we can login with cordova-google-plus plugin. Note: Here we need to use webclientid not reversed client id

else {
  this.googleplus.login({
    'webClientId': 'YOUR CLIENT ID'
  }).then((success) => {
    console.log(success);
    let credential = firebase.auth.GoogleAuthProvider.credential(success['idToken'], null);
    firebase.auth().signInWithCredential(credential).then((data) => {
      console.log(data);
    }).catch((err) => this.displayToast(err));
  }, err => this.displayToast(err));
}

 

Download latest source code

Sundaravel M

About the author: Hey! It's me sundar. (Yea, I'm the founder of codesundar.com). I'm a passionate computer programmer who loves modern web and mobile development. feel free to reach me : Facebook - Twitter - Google+