Add Facebook Native Login to your Ionic App

by - April 02, 2017


Authentication options

Authentication is a key component for your app, and there are some different approaches that you can take.

The handcrafted way (using your own API/Backend)

If you already have an API or backend that handles user authentication, or if you are one of those who like to have strict control over the 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 my clients production apps I use Strongloop. Basically is a platform that enables you to easily build custom API’s for your backend needs. It comes with token based authentication and an AngularJS SDK that works smoothly in your Ionic app. (You can read more about how easy is to manage users in this post “Managing users with StrongLoop”)

The BaaS way

If you don’t want to take care of your own infrastructure and backend implementation, then there are a few BaaS (Backend aa Service) options.
Firebase is a great service that will help you build your app’s backend with ease. (owned by Google). You can read the following tutorial to learn how to Add Firebase authentication to your Ionic App.
The guys from Ionic recently launched the Ionic Platform which is a BaaS solution with very useful services to build mobile apps. This platform offers cool features among push notifications and user authentication. We have made a tutorial to show you how to add Ionic Platform authentication into your Ionic app.

The Social way

You can chose to provide authentication using well known social networks such as Facebook, Instagram, TwitterGoogle, etc. We have made a tutorial to show you how to Add Google+ Login to your Ionic App.
In this post we will explore how to add Facebook native authentication to your Ionic app.
Each option has it’s benefits, 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.

Facebook Authentication

There are different ways to integrate Facebook authentication into your Ionic app. However, only the way covered in this post uses the native approach which uses Facebook app 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 (some of them mentioned below), your users will end up having an awful 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:

The Javascript approach
The Native approach

Facebook authentication using Javascript approach

There are many different libraries you can use to add Facebook javascript login to your app, I will mention just some of them:
  • CordovaOauth is an AngularJS Apache Cordova Oauth library. The purpose of this library is to quickly and easily obtain an access token from various web services to use their APIs. Read more on the official Cordova Oauth documentation.
  • OpenFB is a micro-library that lets you integrate your JavaScript applications with Facebook. It works for both browser-based and Cordova/PhoneGap apps. Read more on the official OpenFB documentation.
  • Facebook SDK for JavaScript with AngularJS. You can interact with the facebook javascript sdk using angular. This is useful both for websites and Ionic apps as Ionic is built with AngularJS. Check “Facebook Javascript SDK integration with AngularJS” to get more information.

Facebook authentication using the native approach

We have already covered all the alternatives, now let’s focus on the one I believe is the best for your projects.
The way it works for hybrid apps to use native api’s and sdk’s is simple, you need a piece (typically a PhoneGap/Cordova plugin) that connects native api’s and sdk’s with the javascript environment where the hybrid apps run. In this case we are going to use a great cordova plugin to interact with the native facebook sdk.

Hands on!

Remember ... you will need:

  • An Ionic app where you will integrate this login. You can either use a blank app, or an existing one.
  • FB API v2.4 but you may be able to make it work with 2.3 and 2.2.
  • Register your Facebook app with Facebook and have an APP_ID. (Don’t panic, we will help you with this.)
  • The Apache Cordova Facebook Plugin to interact with the device native API's
Ad time!: If you are looking for a beautiful starter app with login UI/UX you must have a look at our beautiful mobile themes, templates & components. Specially our Logins Category.

This is how it will look like

iOS

Android

Step 1: Register your Facebook app

In this section I will help you configuring your Facebook 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 project under the tag widget).
    <widget id="com.ionic-facebook-integration.app" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
  • Check Single Sign On

For Android

  • Add platform android
  • Set your Google Play Package Name. You can find your name in your platforms/android/AndroidManifest.xml file.
    <manifest android:hardwareAccelerated="true" android:versionCode="1" android:versionName="0.0.1" package="com.ionic_facebook_integration.app" xmlns:android="http://schemas.android.com/apk/res/android">
  • Check Single Sign On
  • Set the Class Name to com.facebook.LoginActivity
  • Generate your own Key Hash.

Generate your own Key Hash

As you can read here 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. OpenSSL is available for download from OpenSSL.

On OS X, run:
keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore | openssl sha1 -binary | openssl base64

On Windows, use:
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 Login.

You can see this page if you are looking to generate a release key hash.

Step 2: Install required cordova plugins to interact with Facebook native SDK

After you have created you Facebook app and have an APP_ID it’s time to install the plugin into your app. Follow these steps to get this DONE:
  • Open a terminal window and clone this repository on your computer:
    $ git clone https://github.com/Wizcorp/phonegap-facebook-plugin.git
  • Using your terminal window, go to your Ionic app folder
  • If you want to build your app for iOS execute: ionic platform add ios
  • If you want to build your app for Android execute: ionic platform add android
  • Execute the following command on the terminal changing the variables with your own values:
    • The path you cloned the plugin to earlier
    • Replace APP_ID and APP_NAME variables with your Facebook app values
    $ cordova -d plugin add /path_to_cloned/phonegap-facebook-plugin --variable APP_ID="123456789"--variable APP_NAME="myApplication"

What we have done so far:

  • An Ionic app (existing or new one)
  • A Facebook app with the proper configurations
  • Facebook Plugin installed into your Ionic app

Step 3: Adding Login/Logout functionality

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

Login

The best way to show you how to add Login functionality is with a real example of the code, here you can see an AngularJS controller that handles the facebook login for your app.
.controller('WelcomeCtrl', function($scope, $state, $q, UserService, $ionicLoading) {
  // This is the success callback from the login method
  var fbLoginSuccess = function(response) {
    if (!response.authResponse){
      fbLoginError("Cannot find the authResponse");
      return;
    }

    var authResponse = response.authResponse;

    getFacebookProfileInfo(authResponse)
    .then(function(profileInfo) {
      // For the purpose of this example I will store user data on local storage
      UserService.setUser({
        authResponse: authResponse,
    userID: profileInfo.id,
    name: profileInfo.name,
    email: profileInfo.email,
        picture : "http://graph.facebook.com/" + authResponse.userID + "/picture?type=large"
      });
      $ionicLoading.hide();
      $state.go('app.home');
    }, function(fail){
      // Fail get profile info
      console.log('profile info fail', fail);
    });
  };

  // This is the fail callback from the login method
  var fbLoginError = function(error){
    console.log('fbLoginError', error);
    $ionicLoading.hide();
  };

  // This method is to get the user profile info from the facebook api
  var getFacebookProfileInfo = function (authResponse) {
    var info = $q.defer();

    facebookConnectPlugin.api('/me?fields=email,name&access_token=' + authResponse.accessToken, null,
      function (response) {
    console.log(response);
        info.resolve(response);
      },
      function (response) {
    console.log(response);
        info.reject(response);
      }
    );
    return info.promise;
  };

  //This method is executed when the user press the "Login with facebook" button
  $scope.facebookSignIn = function() {
    facebookConnectPlugin.getLoginStatus(function(success){
      if(success.status === 'connected'){
        // The user is logged in and has authenticated your app, and response.authResponse supplies
        // the user's ID, a valid access token, a signed request, and the time the access token
        // and signed request each expire
        console.log('getLoginStatus', success.status);

      // Check if we have our user saved
      var user = UserService.getUser('facebook');

      if(!user.userID){
     getFacebookProfileInfo(success.authResponse)
     .then(function(profileInfo) {
      // For the purpose of this example I will store user data on local storage
      UserService.setUser({
       authResponse: success.authResponse,
       userID: profileInfo.id,
       name: profileInfo.name,
       email: profileInfo.email,
       picture : "http://graph.facebook.com/" + success.authResponse.userID + "/picture?type=large"
      });

      $state.go('app.home');
     }, function(fail){
      // Fail get profile info
      console.log('profile info fail', fail);
     });
    }else{
     $state.go('app.home');
    }
      } else {
        // If (success.status === 'not_authorized') the user is logged in to Facebook,
    // but has not authenticated your app
        // Else the person is not logged into Facebook,
    // so we're not sure if they are logged into this app or not.

    console.log('getLoginStatus', success.status);

    $ionicLoading.show({
          template: 'Logging in...'
        });

    // Ask the permissions you need. You can learn more about
    // FB permissions here: https://developers.facebook.com/docs/facebook-login/permissions/v2.4
        facebookConnectPlugin.login(['email', 'public_profile'], fbLoginSuccess, fbLoginError);
      }
    });
  };
})
Then in your html you should add a “Login with Facebook” button
<a class="facebook-sign-in button button-block" ng-click="facebookSignIn()">Login with Facebook</a>

Logout

The following controller contains all the necessary code for the facebook sign out:
.controller('HomeCtrl', function($scope, UserService, $ionicActionSheet, $state, $ionicLoading){
 $scope.user = UserService.getUser();

 $scope.showLogOutMenu = function() {
  var hideSheet = $ionicActionSheet.show({
   destructiveText: 'Logout',
   titleText: 'Are you sure you want to logout? This app is awsome so I recommend you to stay.',
   cancelText: 'Cancel',
   cancel: function() {},
   buttonClicked: function(index) {
    return true;
   },
   destructiveButtonClicked: function(){
    $ionicLoading.show({
      template: 'Logging out...'
    });

        // Facebook logout
        facebookConnectPlugin.logout(function(){
          $ionicLoading.hide();
          $state.go('welcome');
        },
        function(fail){
          $ionicLoading.hide();
        });
   }
  });
 };
})
Then in your html you should add a “Log out” button
<a class="button button-assertive button-block button-outline" ng-click="showLogOutMenu()">Log Out</a>

Services

You also will need some services to store and get your user’s data. For the purpose of this example I will store user data on the device local storage but you should save it on a database.
angular.module('services', [])
.service('UserService', function() {
  // For the purpose of this example I will store user data on ionic local storage but you should save it on a database
  var setUser = function(user_data) {
    window.localStorage.starter_facebook_user = JSON.stringify(user_data);
  };

  var getUser = function(){
    return JSON.parse(window.localStorage.starter_facebook_user || '{}');
  };

  return {
    getUser: getUser,
    setUser: setUser
  };
});

What we have done so far:

  • At this point you should have an Ionic app with Facebook login and logout functionalities working.





Notes

For XCode issues with iOS9 read this thread.
If you want to build the project for iOS9 and you are getting some errors on xcode, try adding the following code to your platforms/ios/facebook-login/facebook-login-Info.plist file.
<key>LSApplicationQueriesSchemes</key>
<array>
 <string>fbauth</string>
</array>
<key>NSAppTransportSecurity</key>
<dict>
 <key>NSAllowsArbitraryLoads</key>
 <true/>
</dict>

You May Also Like

0 comments