Ionic 3 Gmail Login with Firebase

 

Facebook, Google, Twitter and other third-party service provider are the industry standards for token-based authentication and authorization for the web, desktop, and mobile application. These third-party service providers act as an intermediary on the behalf of the end user allows to login without exposing the user’s password.

We have already done Ionic Firebase login with Facebook in the previous example.  In this example, we learn how to use the Gmail native plugin to authenticate with Ionic through Firebase. For most of the authentication in Ionic through a 3rd party is setting up the configuration and actually writing code in less and easier.

Step #1: Setup the project and Installing the required Plugin

ionic start ionicGmailFirebase blank
npm install firebase --save

I have noticed that while using Firebase in our Ionic project and adding an Android platform for our Ionic project will generate an error. To  solve the error we have to install the plugin below
install promise-polyfill –save-exact

Step 2#: Setup Android app in Firebase Console

In the https://console.firebase.google.com, we to have click on add new project and name it as FirebaseFBlogin.

 

Creating new project will take you to project dashboard in firebase console, we have to get Firebase API for our ionic apps, as we are using Ionic which is hybrid, click on Add Firebase to your web app.

 

Clicking on this button we get the Firebase API config information and add this API code and import firebase in app.components.ts as a highlight.

Modify the app.component.ts and replace this dot with your Firebase API value.

import { Component } from '@angular/core';
.......

import { HomePage } from '../pages/home/home';
import firebase from 'firebase';

var firebaseConfig = {
    apiKey: ".....",
    authDomain: ".....",
    databaseURL: ".....",
    projectId: ".....",
    storageBucket: ".....",
    messagingSenderId: "....."
  };

@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  rootPage:any = HomePage;

  constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen) {
    platform.ready().then(() => {
      statusBar.styleDefault();
      splashScreen.hide();
      firebase.initializeApp(firebaseConfig);
    });
  } 
}

Enable Gmail Sign-In in Firebase
In Firebase console and to enable Gmail authentication for our app. To enable Gmail authentication we need to go to  Firebase Console and locate the app you’re using.
Inside the app’s dashboard, you’re going to go into Authentication > Sign-In Method > Gmail and click the Enable toggle to enable.

 

Step 3 #: Configure Google Credentials

Configure for the Android platform: – In this example, we first create Google credential for Android in our Ionic apps. We have to set separately configuration for ionic Google credential for IOS.

  1. Go to https://developers.google.com/mobile/add?platform=android
  2. For the project name, Google developer is 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.
  3. Android package name type com.edupala.starter2googleLogin from ionic config.xml. By default package name is io.ionic.starter.It is good practice to change default package name.

On clicking on CONTINUE ON will take us to the new window, To enable Gmail Singin in our project, we need to generate an Android Sign in Certificate SHA-1.  Google provides two SHA-1 certificates you’ll need, one for production and one for development. For this example, we are generating SHA-1 certificate for Android development. We need to run a command on terminal.

C:\Users\Username>keytool -exportcert -list -v -alias androiddebugkey -keystore .android/debug.keystore

Where most of the case ~/.android/debug.keystore is on Windows you will find in  C:\Users\Username>  .android is hidden file and copy the SHA-1 certificate and the past in our Google developer and 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.

Configure for ISO Platform:
We had finished Google authentication for Android, now we start configuration for ISO click here. In Google developer is 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.

We have to provide iOS Bundle ID, to get this, go into your app’s 

config.xml

 file and copy the package id of the app. We have already done for Android past the widget ID in iSO bundle and click on CONTINUE TO.

On click on CONTINUE TO will display new window below. we have to enable Google Sign-In, Then we have click on the big button that says Generate Configuration Files, go ahead and click it, it will let you download your file

GoogleService-Info.plist

, which is a config file for iOS.




Step 4 #: Installing GooglePlus native plugin

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

To install the Cordova plugin for Google Plus we have to specify the myreversedclientid, we can get this value from a downloaded file

GoogleService-Info.plist.

. Open this file, copy and past the reversed client ID.

 

Step 5: Ionic Google Plus Login page

We have completed the external configuration, now time to write code for our Google Authentication for Ionic Apps through Firebase. We will add a provider for the authentication code.

 ionic generate provider auth

In src/providers/auth.ts add the following code for Google Plus Firebase authentication

import { GooglePlus } from '@ionic-native/google-plus';
import { Injectable } from '@angular/core';
import { Observable } from "rxjs/Observable";
import firebase from 'firebase/app';


@Injectable()
export class AuthProvider {

  constructor(public googlePlus: GooglePlus) {}

  googleLogin() {
    return Observable.create(observer => {
      return this.googlePlus.login({
        'webClientId': 'Add Web Client ID',
        'offline': true
      })
      .then( res => {
        const firecreds = firebase.auth.GoogleAuthProvider.credential(res.idToken);
        firebase.auth().signInWithCredential(firecreds)
        .then( success => { observer.next(success); })
        .catch(error => {
          observer.error(error);
        });
      });
    })
  }

  logout(){
    firebase.auth().signOut().then(function() {
      alert("logout successful");
    }, function(error) {
      console.log(error);
    });
  }
}

We have to specify the webClientId in the Credentials section in the Google Developer console.  We can get web Client ID from Firebase dashboard -> Authentication -> Inside the Google sign as shown below.

In auth provider class we have added code to login with Google Plus and log out functionality.

Modify src/pages/home/home.ts, we need to import AuthProvider for Google login/logout .

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { GooglePlus } from '@ionic-native/google-plus';
import firebase from 'firebase';
import { AuthProvider } from './../../providers/auth';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html',
  providers: [GooglePlus]
})
export class HomePage {
  displayName: any;
  email: any;
  photoURL: any;
  isLoggedIn:boolean = false;

  constructor(public navCtrl: NavController, public authProvider: AuthProvider) {}

  loginWithGoogle(): void{
    this.authProvider.googleLogin().subscribe((res) => {
        this.email = res.email;
        this.displayName = res.displayName;
        this.photoURL = res.photoURL;
        this.isLoggedIn = true;
    }, err =>{
      console.log(err);
    });  
  }

  logout(){
    this.authProvider.logout();
  }

}

Modify the src/pages/home/home.html, here we are adding two buttons to trigger the login and logout process and displaying user profile information from Google Plus.

<ion-header>
  <ion-navbar color="primary">
    <ion-title>Firebase Auth With Google Plus</ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <div *ngIf="isLoggedIn; else loginTemplate">
    <h1>Welcome, {{displayName}}!</h1>
    <p>Email: {{email}}<br>
      Given Name: {{displayName}}</p>
    <p>
      <ion-avatar item-left>
        <img src="{{photoURL}}">
      </ion-avatar>
    </p>
    <p><button ion-button (click)="logout()">Logout From Google</button></p>
  </div>

  <ng-template #loginTemplate>
    <p><button ion-button (click)="loginWithGoogle()">Login With Google</button></p>
  </ng-template>
</ion-content>

 

At last, we have to register the provider for Google Plus Cordova plugin and we also have to add reference of AuthProvider in app.module.ts file.

import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '@ionic-native/splash-screen';
import { StatusBar } from '@ionic-native/status-bar';

import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { GooglePlus } from '@ionic-native/google-plus';
import { AuthProvider } from '../providers/auth';


@NgModule({
  declarations: [
    MyApp,
    HomePage
  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage
  ],
  providers: [
    StatusBar,
    SplashScreen,
    GooglePlus,
    AuthProvider,
    {provide: ErrorHandler, useClass: IonicErrorHandler}
  ]
})
export class AppModule {}