In this Ionic framework tutorial we are going to show you - step by step - how to integrate Facebook Sign In to your Ionic applications. This will enable an easy and elegant way for your users to log in to your mobile and web apps.

Benefits of adding Facebook Authentication to your Ionic app

  • Build a trusted relationship: Give people control over the info they share with your app.
  • Access profile info: like picture, gender, age, name, without having to ask for it.
  • Improve conversions: Help people log into your app quickly without having to remember another username and password.
  • One login across every device: Make it easy for people to log in and access their info across multiple platforms and devices.

At IonicThemes we are big fans of Learning by example, that's why all our Ionic tutorials include a complete and free Ionic code example that you can reuse in your own projects.

We strive to create the best content for Ionic Framework, both tutorials and templates to help the Ionic community succeed. We work towards empowering developers to achieve a free life through coding. That's what motivates us at IonicThemes everyday.

In this post you will learn how to add Facebook Login to your Ionic app. As an example we are going to build a simple Ionic app that allows users to log in using their Facebook account. Once they log in, they will see a page with their Facebook profile information.

Authentication is an essential part of most applications, and there are different approaches and strategies that you can take. The approach taken for any project depends on its particular application requirements. Let's explore some of these approaches.

Using your own API or Backend

If you already have an API or backend that handles user authentication, or if you like to have tight control over your backend implementation, then this may be your option.

Mobile apps require a different authentication strategy than web apps or websites. You don't have sessions so you have to go with the token based authentication. For our production apps we use and recommend NestJS.

NestJS is basically a Node.js framework that enables you to easily build efficient and scalable server-side applications. The architecture is heavily inspired by Angular so if you are familiar with Angular, you will find very enjoyable to work with Nest. Implementing Authentication using Nest is very straightforward. Learn how to integrate NestJS to your Ionic App.

Using a Backend As A Service

If you don't want to take care of your own infrastructure and backend implementation, then there are a few BaaS (Backend as aService) options.

Firebase is a very popular service that will help you building the backend for your Ionic Framework application. Firebase is a popular tool that helps you build apps fast, without managing infrastructure. It's also a powerful Database as a Service (DBaaS) solution which provides a scalable NoSQL cloud database to store and sync data for client and server side development.

Firebase is built on top of Google infrastructure and allows you to scale automatically, so you don't need to worry about scaling your own servers. You can read the following tutorial to learn how to handle Firebase authentication in Ionic apps.

Using Social Providers

You can choose to provide authentication using well known social networks such as Facebook, Instagram, Twitter, Google, Github, etc.

We think that in these days, this is the best way to authenticate your users because it's easier and faster for them and also for you. Also, remember that providing a good user experience is a key factor, so providing a one click authentication will definitely add up to a good UX (unless you are building a banking application).

We have created a set of detailed Ionic Authentication tutorials to help you adding this functionality to your Ionic app.

So to define the scope of this post, in this tutorial we will explore how to add Facebook authentication to your Ionic app.

Each authentication option has its pros and cons, and of course you can mix them together and have an even more complete solution and experience for your users. It's very common to see different ways of authenticating users within an app.

Update! From April 2020 onwards, if you want to publish your Ionic application on the Apple App Store, you also need to add Sign in with Apple. Why? Because they say so and they control their market (not happy with this? Build a PWA!).

The Apple guidelines states: "Apps that exclusively use a third-party or social login service (such as Facebook Login, Google Sign-In, Sign in with Twitter, Sign In with LinkedIn, Login with Amazon, or WeChat Login) to set up or authenticate the user's primary account with the app must also offer Sign in with Apple as an equivalent option." But, it also says: "Sign in with Apple is not required if: Your app exclusively uses your company's own account setup and sign-in systems."

If you need help building your Ionic App, you can check Ionic 5 Full Starter App.

It will save you hundreds of hours of development and design and it already has lots of useful features that you will love such as Facebook Login. These are some of the authentication screens available in the template.

Ionic facebook authentication
Ionic facebook authentication
Ionic facebook authentication

There are different ways to integrate Facebook authentication into your Ionic app. However, not all of them use the native approach which uses the Facebook Application to perform the login instead of opening a popup requesting users to enter their credentials to login to Facebook before granting access to your app.

What does this mean? If you choose to integrate other libraries, your users will end up having a bad user experience as they will be prompted to enter their Facebook username and password each time your app requests authorization from Facebook.

Using the native approach we cover in this post, if users have the Facebook app installed on their devices, the authorization flow will be unobtrusive without requiring users to perform unnecessary extra steps.

This comparison illustrates the difference mentioned above:

Javascript approach:

Ionic facebook login

Native approach:

Ionic facebook login

The way it works for hybrid apps to use native API's and SDK's is very simple. We need a piece (typically a Cordova plugin) that connects native API's and SDK's with the javascript environment where the ionic app runs. For this example ionic app we are going to use a cordova plugin to interact with the Facebook SDK.

We will use the Facebook Cordova Plugin to perform Facebook authentication on iOS and Android.

For this Ionic example app you will need:

  • An Ionic app where you will integrate this functionality. You can either use a Ionic blank app, or an existing one.
  • Fabric API key.
  • Register a Facebook App with Facebook and have an APP_ID. (Don’t panic, we will help you with this.)
  • The Facebook Cordova Plugin to interact with the device native API's.

Our Ionic demo app will look like this:

Ionic facebook app
Ionic facebook app
Ionic facebook app

In this section I will help you creating and configuring your Facebook application in order to enable sign in operations from an Ionic app.

For iOS

  • Add platform iOS
  • Set your Bundle ID. You can find your ID in your config.xml file on the root of your Ionic project under the tag widget.

    <widget id="io.ionic.facebook.login" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
  • Check Single Sign On

    facebook app configurations

For Android

  • Add platform android
  • Set your Google Play Package Name. You can find your name in your platforms/android/app/src/main/AndroidManifest.xml file from your Ionic project.

    <manifest android:hardwareAccelerated="true" android:versionCode="1" android:versionName="0.0.1" package="io.ionic.facebook.login" xmlns:android="http://schemas.android.com/apk/res/android">
  • Check Single Sign On
  • Set the Class Name to com.facebook.FacebookActivity
  • Generate your own Key Hash.

    facebook app configurations

Generate a Key Hash

As explained in the facebook documentation, to run samples apps quickly, you 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.

On OS X, run:

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

On Windows, you will need the following:

Run the following command in a command prompt in the Java SDK folder:

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

This generates a 28 character string. You can add multiple key hashes if you develop with multiple machines. You can now compile and run all of the samples - including those that use Facebook Native Login.

If you are looking to generate a release key hash please refer to this page.

If you're short on time, our Ionic Starter Template has Facebook Login out of the box. It will save you hundreds of hours of development and design. These are some of the authentication screens available in the template.

ionic authentication
Ionic Login
Authentication in Ionic Apps

Once you have created your Facebook application and have an APP_ID , it is time to install the plugin in your application. Follow these steps to do this:

  • Execute the following command on the terminal changing the variables with your own values:
    • Replace APP_ID and APP_NAME variables with your Facebook app values

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

    $ npm install --save @ionic-native/facebook

What we have done so far:

  • Created an Ionic app (or used a existing one)
  • Created a Facebook app with the needed configurations
  • Installed Facebook Cordova Plugin in our Ionic app

Now we will go straight to the code so open your Ionic app with your preferred code editor. Personally I use and recommend atom.

We don't want to ask users to log in each time they open the app because it would be annoying. To solve this we will use Native Storage to save the user data the first time they log in.

Native Storage

Native Storage is a Cordova plugin which provides persistent storage of primitives native in Android, iOS and Windows. It's created because of the non-persistent property of Local Storage in the WebView of Android and iOS. In iOS stored data from LocalStorage can be removed by the OS, when running out of memory.

To install native storage plugin just run the following commands in your ionic project:

$ ionic cordova plugin add cordova-plugin-nativestorage --save$ npm install --save @ionic-native/native-storage

To know if the user is already logged in, we will add the following code to check this in the platform.ready() in app.component.ts.

constructor(
  private platform: Platform,
  private splashScreen: SplashScreen,
  private statusBar: StatusBar,
  private nativeStorage: NativeStorage,
  private router: Router
) {
  this.platform.ready().then(() => {
    // Here we will check if the user is already logged in
    // because we don't want to ask users to log in each time they open the app
    this.nativeStorage.getItem('facebook_user')
    .then( data => {
      // user is previously logged and we have his data
      // we will let him access the app
      this.router.navigate(["/user"]);
      this.splashScreen.hide();
    }, err => {
      //we don't have the user data so we will ask him to log in
      this.router.navigate(["/login"]);
      this.splashScreen.hide();
    });

    this.statusBar.styleDefault();
  });
}

Ionic Facebook Log In

The best way to show you how to add log in functionality to your Ionic Framework App is with a real example of the code, here you can see some Typescript code that handles the all the twitter authentication for your ionic app.

import { Component } from '@angular/core';
import { Facebook } from '@ionic-native/facebook/ngx';
import { Router } from '@angular/router';
import { NativeStorage } from '@ionic-native/native-storage/ngx';
import { LoadingController } from '@ionic/angular';


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

  constructor(
    private fb: Facebook,
    private nativeStorage: NativeStorage,
    public loadingController: LoadingController,
    private router: Router,
    private platform: Platform,
    public alertController: AlertController
  ) {}

  async doFbLogin() {
    const loading = await this.loadingController.create({
      message: 'Please wait...'
    });
    this.presentLoading(loading);
    let permissions = new Array<string>();

    // the permissions your facebook app needs from the user
    const permissions = ["public_profile", "email"];

    this.fb.login(permissions)
    .then(response =>{
      let userId = response.authResponse.userID;

      // Getting name and gender properties
      this.fb.api("/me?fields=name,email", permissions)
      .then(user =>{
        user.picture = "https://graph.facebook.com/" + userId + "/picture?type=large";
        //now we have the users info, let's save it in the NativeStorage
        this.nativeStorage.setItem('facebook_user',
        {
          name: user.name,
          email: user.email,
          picture: user.picture
        })
        .then(() =>{
          this.router.navigate(["/user"]);
          loading.dismiss();
        }, error =>{
          console.log(error);
          loading.dismiss();
        })
      })
    }, error =>{
      console.log(error);
      loading.dismiss();
    });
  }

  async presentLoading(loading) {
    return await loading.present();
  }
}

Ionic Facebook Log Out

To perform Facebook log out we will call the fb.logout() method that will invalidate the token generated at log in. Also, we will remove from the native storage the data from the logged user.

import { Component, OnInit } from '@angular/core';
import { Facebook } from '@ionic-native/facebook/ngx';
import { Router } from '@angular/router';
import { NativeStorage } from '@ionic-native/native-storage/ngx';
import { LoadingController } from '@ionic/angular';

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

export class UserPage implements OnInit {

  user: any;
  userReady: boolean = false;

  constructor(
    private fb: Facebook,
    private nativeStorage: NativeStorage,
    public loadingController: LoadingController,
    private router: Router,
  ) {}

  async ngOnInit() {
    const loading = await this.loadingController.create({
      message: 'Please wait...'
    });
    await loading.present();
    this.nativeStorage.getItem('facebook_user')
    .then(data =>{
      this.user = {
        name: data.name,
        email: data.email,
        picture: data.picture
      };
        loading.dismiss();
        this.userReady = true;
    }, error =>{
      console.log(error);
      loading.dismiss();
    });
  }

  doFbLogout() {
    this.fb.logout()
    .then(res => {
      // user logged out so we will remove him from the NativeStorage
      this.nativeStorage.remove('facebook_user');
      this.router.navigate(["/login"]);
    }, error =>{
      console.log(error);
    });
  }
}

Testing the implementation

At this point you should have an Ionic application with Facebook log in and log out functionalities. To test the native implementation you need to test the application in a real device or in an emulator because Cordova isn't available on the browser.

If you are new to Ionic development you can check how to Run your Ionic app in different environments.

Remember you can download all the source code of this Ionic tutorial by clicking the GET THE CODE button from the beginning of this page.

Did you know that we recently released Ionic 5 Full Starter App - PRO version? It's an Ionic PWA template that you can use to jump start your PWA development and save yourself hundreds of hours of design and development. Try it on your phone as a PWA.

ionic 5 starter

Authentication is an essential part of most applications, and there are different approaches and strategies that you can take. The approach taken for any project depends on its particular application requirements. Let's explore some of these approaches.

In this post we explained how to add Facebook Sign In to an Ionic Framework application. We built a demo app that you can download and use for free to build your own Ionic application.

To add the log in functionality we used Facebook Cordova plugin. It enables a native log in both in iOS and Android apps.

If you have any issues or questions about this tutorial please leave a comment below.

If you want to keep learning Ionic Framework, I suggest you the following tutorials:

At IonicThemes we are big fans of Learning by example, that's why all our ionic tutorials include a complete and free ionic code example that you can reuse in your ionic projects.

We strive to create the best content for Ionic Framework, both tutorials and templates to help the Ionic community succeed. We work towards empowering developers to achieve a free life through coding. That's what motivates us at IonicThemes everyday.

Also, you can check out our detailed and professional Ionic Starter App crafted with love and dedication to help you create better apps and supercharge your productivity.