How to implement Ionic facebook login and Ionic firebase Facebook authentication

In ionic we can use 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. We can easily implement ionic Facebook login using different methods. These third-party service providers act as an intermediary on the behalf of the end-user allows them to log in without exposing the user’s password.

In this article, we have two goals behind this tutorial. First, we’ll first learn how to use Ionic Facebook connect to login into Mobile devices. Secondly, if you are using Firebase as a backend then we can use the AngularFire library to log in to our app through Facebook. Let’s get started.

Setting up an Ionic Firebase login project

With the release of ionic version 4, the Ionic framework is no longer limited to angular. Ionic allows us to create ionic projects in different front-end frameworks like Angular, Vue, and React. Let first create a blank Ionic Angular project for our ionic firebase Facebook authentication example.

ionic start ionicFacebookEx blank --type=angular

Create and configure Facebook authentication setting in Facebook developer site

In the  https://developers.facebook.com/apps and we have to create a new app in Facebook’s developer dashboard and this app in the Facebook developer will use to ask our users for their permission wot log them into our Ionic application. 

We have to click on Create App, it will create a new project and will take us to the Facebook app project dashboard, we have to complete few tasks. We have our Facebook APP ID and App secret, which we need if we are using Firebase as a backend. To enable Facebook login, in the Facebook project dashboard we need to add Facebook Login to our project. Here is a screenshot of adding Facebook products to our project.

Ionic facebook login

First, we will select the app category as “Apps for Pages”.

Is for Firebase Facebook authentication

If you are not using Ionic Firebase, then you can skip this step. We have to copy both Facebook App ID and App Secret key and past these values to the Firebase Facebook authentication console.

Enable Facebook Sign-In in Firebase: In Firebase console and enable Facebook authentication for our app. To enable Facebook 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 > Facebook and click the Enable toggle to enable. We need to copy and paste both Facebook App ID and App Secret in the Firebase Facebook authentication method.

AppDomains: In the Facebook project dashboard, we can copy this value from the Firebase Facebook authentication method at the end we have OAuth redirect URI to your Facebook app configuration copy this value from firebase, and paste in AppDomain

In this example, we learn how to use the Facebook native plugin to authenticate with Ionic through Firebase.

Configure to add Facebook platform for our project

In the Facebook dashboard, we will add the platform for the website, the Android platform, and IOS for Apps.  To add the platforms, inside your Facebook dashboard click on settings, then, at the right bottom of the app’s information you’ll see a button that says Add Platform, click it.

You’ll get a prompt asking you which platform, adding the platform for website and IOS are straightforward as in the image below.

  1. For a website, just add the value from the Authorised domain from the Firebase console of the authentication option if you are using firebase which we have discussed above.
  2. For IOS we have to add Ionic app ID from config.xml and by default, it is io. ionic.start, but in our case, we had to change its value to com.edupala.fblogin by default value is io.ionic.start.
  3. Configure an Android platform for Facebook setting is a little bit tricky. we have to fill two fields for adding the Android platform. Inside the Ionic app, we will get the ID from config.xml and by default, it is io.ionic.start, in our case is com.eduplala.fblogin and past this value in Google play package name and Class Name is optional. We also have to specify the key hashes value of our Ionic app if we are using Ionic Facebook connect plugin only. If you are using angularFire library for the web then no need for it.

Getting key hashes value is a little bit tricky, till now we didn’t add any code related to Facebook authentication, first we will set all the configure and will add authentication code later.

Step for Getting key Hashes for Ionic app for Facebook

To run apps quickly, we can generate key hashes for your development environments. Add these to your Facebook developer profile for the sample apps. Keytool, for generating the key hashes, is included with the Java SE Development Kit (JDK) that you installed as part of setting up your development environment. Run the following key.

// For IOS and linux

keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore | openssl sha1 -binary | openssl base64

// On Windows, run:

keytool -exportcert -alias androiddebugkey -keystore %HOMEPATH%\.android\debug.keystore | openssl sha1 -binary | opensslbase64

Note: By running the above command if you get 18 characters, then it is Base64 and you can copy it directly and paste this value in the Facebook dashboard key hash value. But if we get the SHA1 value then we have to convert the SHA1 value to base 64. You will get some hexadecimal value and copy the SHA1 value to your clipboard like this 6C:E0:80:2D:60:5C:68:FD:FA:0A:6C:E5:5A:72:64:DD:26:8D:44:84

We have to convert this hex value to SHA1 value from this website open this site http://tomeko.net/online_tools/hex_to_base64.php to convert your SHA1 value to base64.  This is the SHA1 value for key hashes and the past in Key Hashes Facebook Android app dashboard.

We have to add the Facebook native plugin in our apps, we have already got our Facebook App ID and app name from developers. facebook.com dashboard. Replace the App ID and app name with your ID and app name.

$ ionic plugin add cordova-plugin-facebook4 --variable APP_ID="456565" --variable APP_NAME="myApplication"

Ionic Facebook login using Facebook connect plugin

Now we have done all the external configuration and now it is time to demonstrate our first example of Ionic facebook authentication using the Facebook Connect plugin. Let’s add our Cordova plugin in our project.

 ionic cordova plugin add cordova-plugin-facebook-connect --variable APP_ID="123456789" --variable APP_NAME="myApplication"

Above APP_ID and APP_NAME are for demo only, you have to copy this value from your Facebook developer project dashboard. We need to install the Facebook Cordova plugin as follows.

npm install cordova-plugin-facebook-connect
npm install @ionic-native/facebook
ionic cap sync

Create Authentication service for Login Activities

We need a service to handle authentication activities, it recommends an approach to use a service that hides direct access of data to the rest of the application. Service allows us to share our data across applications. We need to create a service that can be used to perform authentication and determine whether the application has been authenticated. Let run the following command to generate auth service.

ionic generate service services/auth

We need to display user data from our Facebook profiles on our Ionic Facebook page. Let create a user model, create folder models in-app and add user.ts file and add the following data for the user model.

export interface IUser {
    username: string; 
    email: string; 
    photoURL: string;
}

Add the following code in services/auth.service.ts file for our Facebook authentication login.

import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { Facebook, FacebookLoginResponse } from '@ionic-native/facebook/ngx';
import { IUser } from '../models/user';

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  user: IUser;

  constructor(
    private router: Router,
    private fb: Facebook) { }

  loginWithFacebook() {
    this.fb.login(['public_profile', 'user_friends', 'email'])
      .then((res: FacebookLoginResponse) => {
        this.getUserDetail(res.authResponse.userID);
        console.log('Logged into Facebook!', res)
      })
      .catch(e => console.log('Error logging into Facebook', e));
  }

  getUserDetail(userid: any) {
    this.fb.api('/' + userid + '/?fields=id,email,name,picture', ['public_profile'])
      .then((res: any) => {
        console.log(res);
        debugger
        this.user = { email: res.email, username: res.name, photoURL: res.picture.data.url };
        debugger
        if (this.user) {
          this.router.navigate(['/home']);
        }
      })
      .catch(e => {
        console.log(e);
      });
  }
}

In our auth service, we have two methods, first to authenticate using Facebook by using Ionic native Facebook login, and the second method we need to retrieve user data by using Facebook user id. Here is a screenshot of Ionic facebook login success.

Ionic facebok login success

Create Login page and home page to display user information

By default, we have a home page and let add another page called login, by running the following command.

ionic generate page login

This tutorial is to demonstrate Ionic facebook login, in real application we have a signup page, and different third-party OAuth methods. We need to edit app.routing page to make login as the home page and edit the app.routing.module.ts file.

import { NgModule } from '@angular/core';
import { PreloadAllModules, RouterModule, Routes } from '@angular/router';

const routes: Routes = [
  {
    path: 'login',
    loadChildren: () => import('./login/login.module').then(m => m.LoginPageModule)
  },
  {
    path: '',
    redirectTo: 'login',
    pathMatch: 'full'
  },
  {
    path: 'home',
    loadChildren: () => import('./home/home.module').then(m => m.HomePageModule)
  },

];

@NgModule({
  imports: [
    RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })
  ],
  exports: [RouterModule]
})
export class AppRoutingModule { }

In login page we add a button to login with facebook() and edit login.page.html template.

<ion-header>
  <ion-toolbar>
    <ion-title>login</ion-title>
  </ion-toolbar>
</ion-header>

<ion-content>
  <ion-button (click)="facebook()">Login With Facebook</ion-button>
</ion-content>

In the home.ts file, we have to complete the following task.

  1. To import the Firebase and Facebook plugin.
  2. Implement the method facebook

In the facebook() method we consume our authService facebook method, let edit login.page.ts

import { Component } from '@angular/core';
import { AuthService } from '../services/auth.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.page.html',
  styleUrls: ['./login.page.scss'],
})
export class LoginPage {

  constructor(private authService: AuthService) { }

  facebook() {
    this.authService.loginWithFacebook();
  }

}

On our home page, we are displaying user information when the user successfully authenticates through Facebook it will navigate to the home page. Let edit the home.page.ts file to get user information from authService.

import { Component } from '@angular/core';
import { IUser } from '../models/user';
import { AuthService } from '../services/auth.service';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {
  user: IUser;

  constructor(private authService: AuthService) {
    this.user = this.authService.user;
   }
}

In the home page template we have a display user name, email, and profile image from Facebook. Let edit home.page.html

<ion-header [translucent]="true">
  <ion-toolbar>
    <ion-title>
      Ionic Facebook Login - User Information
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content [fullscreen]="true">
  <div *ngIf="user; else noUser">
    <p>Name: {{ user.username }}</p>
    <p>Email: {{ user.email }}</p>
    <ion-img [src]="user.photoURL"></ion-img>
  </div>
  <ng-template #noUser>
    No user information
  </ng-template>

</ion-content>

Ionic Facebook login using AngularFire

We need to create a project or continue from our previous project, So first we need to install Firebase and AngularFire library. AngularFire is an official angular library to implement Firebase functionalities in the Angular project, as we are using the Ionic Angular project. If you are using Firebase as a serverless backend, then we can use the AngularFire library to authenticate users. Let install these libraries.

npm install firebase –-save

We can install firebase first and then we can add angularFire as

ng add @angular/fire

If we are running the above command to add AngularFire then we first need to set up or configure our firebase project. In this article, we’ll focus only on Ionic Firebase Facebook authentication. Check our previous articles on how to configure and setting up the Firebase project and enabling different sign-in methods. In previous articles, we have enabled Google authentication in Ionic firebase, it same procedure for Facebook but we need to add Facebook project APP_ID and secrete key from the Facebook dashboard, which we have already covered above.

Create Authentication service for Login Activities

We need a service to handle authentication activities, in our example, we are implementing Ionic Firebase Facebook authentication logic. Let run the following command to generate auth service.

ionic generate service services/auth

In src/app/services/auth.service.ts add the following code for Ionic Firebase Facebook authentication. If you also need Google authentication and regular email with password authentication, then we have already covered it in our previous articles and check it.

import { Injectable } from '@angular/core';
import { AngularFirestore } from '@angular/fire/firestore';
import { ActivatedRoute, Router } from '@angular/router';
// import * as firebase from 'firebase';
import firebase from 'firebase/app';
import { Observable, of } from 'rxjs';
import { switchMap } from 'rxjs/operators';
import { AngularFireAuth } from '@angular/fire/auth';
import { IUser } from '../models/user';

@Injectable({
  providedIn: 'root'
})
export class AuthService {

  appUser$: Observable<IUser>;

  constructor(
    public afAuth: AngularFireAuth,
    private route: ActivatedRoute,
    private router: Router,
    private db: AngularFirestore) {

    // Get the auth state, then fetch the Firestore user document or return null
    this.appUser$ = this.afAuth.authState.pipe(
      switchMap(user => {
        // If the user is logged in, return the user details.
        if (user) {
          return this.db.doc<IUser>(`appusers/${user.uid}`).valueChanges();
        } else {
          // If the user is NOT logged in, return null.
          return of(null);
        }
      })
    );
  }


  async facebookLogin() {

    const provider = new firebase.auth.FacebookAuthProvider();
    provider.addScope('user_birthday, email, public_profile');


    firebase.auth().signInWithRedirect(provider);
    firebase.auth()
      .getRedirectResult()
      .then((result) => {
        if (result.credential) {
          debugger
          /** @type {firebase.auth.OAuthCredential} */
          const credential: any = result.credential;

          // This gives you a Facebook Access Token. You can use it to access the Facebook API.
          const token = credential.accessToken;

          // Update or Add user profile
          this.updateUserData(result.user);
        }
        // The signed-in user info.
        const user = result.user;
      }).catch((error) => {
        // Handle Errors here.
        const errorCode = error.code;
        const errorMessage = error.message;
        // The email of the user's account used.
        const email = error.email;
        // The firebase.auth.AuthCredential type that was used.
        const credential = error.credential;
        // ...
      });
  }


  // Save the user data to firestore on login
  private updateUserData(user) {
    const userRef = this.db.doc(`appusers/${user.uid}`);
    debugger
    const data = {
      name: user.displayName,
      email: user.email,
      photoURL: user.photoURL
    };
    this.router.navigateByUrl('/home');
    return userRef.set(data, { merge: true });
  }
}

 Firebase provides a lot of authentication options as login through social network authentication eg Facebook and Google etc.  We have used and inject AngularFire in our auth service constructor. In our auth service, we first have a method to authenticate through Facebook, and then we use Facebook user data to save in Firebase appUsers collection.

Here we have appUser$ observable variable, whenever user authentication state changes we either setting it null or user information. If user authentication is login, then we have appUser$ content user information and we can use this observable to display user data in our components or pages.

Note: When the user authenticated through Facebook is successful, then we will redirect the user to the home page, where the home page containing our Firebase activities. Let’s create a login page to add a button to login through Facebook. Here is a screenshot of our example.

Ionic firebase authentication

In this tutorial we are only focusing on Ionic Firebase Facebook authentication let create and edit Login page.

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

import { IUser } from 'src/app/models/user';
import { AuthService } from '../../services/auth.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.page.html',
  styleUrls: ['./login.page.scss'],
})
export class LoginPage {

  constructor(private authService: AuthService) { }

  facebookAuth(): void {
    this.authService.facebookLogin();
  }
}

Edit login.page template to add Facebook login button.

<ion-header>
  <ion-toolbar color="primary">
    <ion-title>Login</ion-title>
  </ion-toolbar>
</ion-header>

<ion-content>
  <div class="login-container">
    <ion-item-group class="ion-padding group">
      <ion-item class="ion-margin-vertical" (click)="facebookAuth()">
        <ion-icon slot="start" name="logo-facebook" color="tertiary"></ion-icon>
        <ion-label>Continue with Facebook</ion-label>
        <ion-icon slot="end" name="arrow-forward-outline"></ion-icon>
      </ion-item>
    </ion-item-group>
  </div>
</ion-content>

Once a user is successful in login we can display user information on our page let’s say home page. Let edit the home.page to consume appUser$ observable to display user data when successful authenticate.

import { Component, OnDestroy, OnInit } from '@angular/core';
import { AngularFireAuth } from '@angular/fire/auth';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { IUser } from '../models/user';
import { AuthService } from '../services/auth.service';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage implements OnInit, OnDestroy {
  appUser: IUser;

  private unsubscribe$ = new Subject<void>();

  constructor(
    private afAuth: AngularFireAuth,
    private authService: AuthService) { }

  ngOnInit() {
    this.authService.appUser$.subscribe(appUser => this.appUser = appUser);
    this.quoteService.getAllQuotes()
      .pipe(takeUntil(this.unsubscribe$))
      .subscribe(result => {
        this.quotes = result;
      });
  }

  ngOnDestroy() {
    this.unsubscribe$.unsubscribe();
  }

}

In home.page template le display user information and let edit home.page.html

<ion-header [translucent]="true">
  <ion-toolbar color="primary">
    <ion-title>
      Ionic firebase Facebook
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content [fullscreen]="true">

  <ng-container *ngIf="appUser; else anonymousUser">
    <p>{{ appUser.name }}</p>
    <p>{{ appUser.email }}</p>
    <ion-img [src]='appUser.photoURL'></ion-img>
  </ng-container>

  <ng-template #anonymousUser>
    User data not available
  </ng-template>

</ion-content>

Conclusion
In this article, we have explored how to implement Ionic facebook login using Facebook connect plugin and AngularFire auth in Ionic Angular applications. AngularFire library is an official angular library to implement firebase activities like authentication, storing data, manipulate data in firebase.

2 thoughts on “How to implement Ionic facebook login and Ionic firebase Facebook authentication”

  1. Good night,
    thanks for the tutorial, it was really good.
    but i have problem when access data from JSON.stringify(success). for example i want to display name so i was make:
    let result = JSON.stringify(success);
    let name = result.user.displayName;

    but i have error message [object object]
    how can i access the json?
    thank you

  2. Hi Arief, Once you successful login with Facebook, all your authentication record are stored in authentication database in firebase. Now I guess you can use AngularFirAuth to access the profile record. Just try this

    import { AngularFireAuth } from ‘angularfire2/auth’;

    constructor(public auth: AngularFireAuth, ….) {
    if (auth.auth.currentUser !== null) {
    this.id = auth.auth.currentUser.uid;
    this.displayName = auth.auth.currentUser.displayName;
    this.email = auth.auth.currentUser.email;
    this.photoURL = auth.auth.currentUser.photoURL;
    }

     

    In template you can access profile information as 

    <div *ngIf=”auth.auth.currentUser”>
    <ion-card padding>
    <ion-card-content>
    <img src=”{{displayName}}“/>

    …… so on
    </div>

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top