Logo
  • TEMPLATES
  • TUTORIALS
  • ANGULAR TEMPLATES
  • REGISTER
  • LOGIN

Learn Ionic Framework with free step by step ionic tutorials

All you have to know about Ionic Framework, the best tips and free code examples so you can get the most out of Ionic Framework.

Add Facebook Native Login to your Ionic App

By Dayana Jabif / posted on October 1, 2015
GET THE CODE

Register

Ionic 1AuthenticationFacebook LoginLogin
  • Post Summary
  • Requirements

In this post you will learn how to add Facebook Native Login to your Ionic app. I will explain you why I think this approach is the best you can take.

As an example we are going to build a simple app that allows users to login to your app using their Facebook account. Once they log in, they will see a home page with their basic profile info.

Requirements

  • You need an Ionic app where you will integrate this login. You can either use a blank app, or an existing one.
  • This tutorial was made using 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

References

  1. Phonegap Facebook Plugin
  2. Facebook Developers


Note: This post is for Ionic 1. If you are working with Ionic 3, 4 or 5 go to Add Facebook Authentication to an Ionic App.

Introduction

Congratulations, you have made a great decision by choosing Ionic to build your app. (You can read more why I believe this in this post “Ionic FTW”).

In this blog you will find lots of content that will guide you on building and shaping beautiful mobile apps.

In particular, this post will be about adding Facebook NATIVE authentication to your Ionic app. This will enable an easy and elegant way for your users to login to your app.

Why adding Facebook Authentication into your app will benefit you and your users?

  • 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.
  • 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.

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 as a 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 Social way

You can choose to provide authentication using well known social networks such as Facebook, Instagram, Twitter, Google, 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.
  • Go to your Facebook app dashboard
  • Click the settings option on the left menu

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 Authentication.

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 authentication 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 authentication 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>

Next Steps

After having the authentication working you can focus on:

  • Learn how to build a complete Ionic app step by step
  • The routing and adding access control to certain pages within your app
  • Store users and tokens in your own database
  • Using analytics tools to track users and what they do in your app
  • Integrate other authentication methods so your users have more options to choose from.
  • Prettifying your app using a theme or your design skills, taking advantage of the many possibilities that Ionic and Sass provide
  • Integrate and make use of other Facebook API endpoints to give more powers to your app.

As you know we also sell beautiful mobile themes, templates and components that you may find super useful as they save you hours of development, time and effort, while giving your projects a great design from scratch. Having said that we have a line of Login / Authentication components that would be the perfect match for your Facebook Native integration.

The authentication step is the first screen of your app that your users will see, so it’s very important that you pay attention to its appearance.

Here you can experience some of the components we have to offer you:

Enjoyed reading this Ionic Tutorial?

Subscribe to keep learning Ionic Framework! You will receive offers, new ionic tutorials and free code examples from IonicThemes.

Watch these videos and start building your Ionic apps now!

Prefer videos?
Check our
YouTube Channel
Author

By Dayana Jabif

Full stack developer and JS lover. Motivated by living a free & happy life.
Follow me on

IONIC TUTORIALS

AdMobApp ShellAuthenticationBeginnersCamera AccessCapacitorDatabaseDesign TipsFacebook LoginFirebase IntegrationForm ValidationsFormsGeolocationGoogle LoginGoogle MapsGoogle PlacesInternationalizationIonic 1Ionic 2Ionic 3Ionic 4Ionic 5LocalizationLoginNavigationProgressive Web AppsPush NotificationsSocial SharingStencilTwitter LoginUIUXWeb ComponentsWordpress Integration

ionic templates

TABLE OF CONTENT

  • Introduction
  • Authentication Options
  • Facebook Authentication
  • Hands On!
  • Step 1: Register your Facebook app
  • Step 2: Install required cordova plugins to interact with Facebook native SDK
  • Step 3: Adding Login/Logout functionality
  • Notes
  • Next Steps

angular templates
There are no products matching the selected filters

Liked this Ionic Tutorial? Leave your comments below.


Sign up to receive offers and ionic free code examples!
FOLLOW US

Our aim is to help people of different skill levels - designers or developers - get the most out of Ionic Framework by saving your expensive time and providing great resources for you to learn ionic framework faster and better. In IonicThemes you will find premium Ionic Starters and Ionic Framework tutorials, tips and tricks.

RESOURCES
  • IONIC STARTERS
  • IONIC TUTORIALS
  • ANGULAR TEMPLATES
  • DESIGN INSPIRATION
SUPPORT
  • FAQS
  • CONTACT US
OTHERS
  • AFFILIATES
  • ABOUT US
  • TERMS & CONDITIONS
  • PRIVACY POLICY
2020 StartApp Labs
Mobile Analytics