Login with Ionic 3 and Cordova Native Facebook Connect Plugin

by Didin J. on Sep 04, 2017 Login with Ionic 3 and Cordova Native Facebook Connect Plugin

Step by step tutorial on Login with Ionic 3 and Cordova Native Facebook Connect Plugin.

This step by step tutorial on Login with Ionic 3 and Cordova Native Facebook Connect Plugin will begin with the Facebook setup from Facebook Developers Dashboard. Previously, we have done a tutorial of authentication or log in using Google+ and LinkedIn. The following tools, dependencies, modules, and plugin are required for accomplishing this tutorial:

- Node.js
- Ionic 3
- Cordova
- Cordova Facebook Plugin
- Text Editor or IDE
- Terminal or Node command line


1. Setup Facebook App

To setup Facebook App and get an App ID/Secret, go to Facebook Developers Dashboard. Login with your Facebook developers account.

Login with Ionic 3 and Cordova Native Facebook Connect Plugin - Facebook Developers Dashboard

Click `+ Add a New App` button. Enter display name then click `Create App ID` button.

Login with Ionic 3 and Cordova Native Facebook Connect Plugin - Facebook Create App

Now, you can see App ID and Secret, write it to your notepad.

Login with Ionic 3 and Cordova Native Facebook Connect Plugin - Facebook App Dashboard

Next, click `Choose Platform` button.

Login with Ionic 3 and Cordova Native Facebook Connect Plugin - Facebook add platform

Choose iOS first then on the iOS wizard scroll down to bottom to enter iOS bundle ID that will supply on `config.xml` later.

Login with Ionic 3 and Cordova Native Facebook Connect Plugin - Facebook add platform wizard

Click next then scroll down and back to App dashboard. Click again `Add Platform` on the Settings menu for setup Android App.

Login with Ionic 3 and Cordova Native Facebook Connect Plugin - Facebook Add another platform

Choose Android, fill the Google Package Name then click Save Changes button.

Login with Ionic 3 and Cordova Native Facebook Connect Plugin - Facebook Android Platform

One more thing for Android app, it needs key hashes. To get the key hashes, especially in development build open the terminal or command line then type this command.

keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android

It will display something like this.

Alias name: androiddebugkey
Creation date: Nov 8, 2015
Entry type: PrivateKeyEntry
Certificate chain length: 1
Certificate[1]:
Owner: CN=Android Debug, O=Android, C=US
Issuer: CN=Android Debug, O=Android, C=US
Serial number: 5e9752f4
Valid from: Sun Nov 08 22:25:34 WIB 2015 until: Tue Oct 31 22:25:34 WIB 2045
Certificate fingerprints:
     MD5:  0A:2D:96:6B:B8:84:F7:37:2E:7E:83:09:43:BB:B7:D4
     SHA1: 2B:52:02:F0:82:94:34:68:FC:B6:DD:81:1D:3A:66:D7:57:3B:B9:11
     SHA256: B1:40:EB:9D:03:50:A2:0F:F2:D4:1B:6D:AA:F6:F9:6A:57:52:B0:70:5A:3C:87:9E:15:F0:BE:7C:90:00:DA:51
     Signature algorithm name: SHA256withRSA
     Version: 3

Extensions:

#1: ObjectId: 2.5.29.14 Criticality=false
SubjectKeyIdentifier [
KeyIdentifier [
0000: C0 3A D3 06 65 23 89 A1   5D 80 CC 55 88 D8 BD 23  .:..e#..]..U...#
0010: 80 6E 67 01                                        .ng.
]
]

You just need to convert SHA1 hex to be base64 characters. We are using this tools for converting it. Just copy and paste SHA1 value that displayed on the terminal to hex string on that site then click the convert button. Now, you get the base64 value that will be copied to Facebook Android app key hashes. Finally, click again Save Changes button.


2. Create a New Ionic 3 App

Open the terminal or Node command line then go to your projects folder. Type this command to create a new Ionic 3 app.

ionic start ionic-facebook tabs

That command will create a new Ionic 3 app using the app name `ionic-facebook` and use tabs view template. Just wait few minutes because it also installs `npm` modules. Now, go to your newly created project.

cd ionic-facebook

To check make sure app working, just type this command.

ionic serve --lab

You will this page if the Ionic 3 app working.

Login with Ionic 3 and Cordova Native Facebook Connect Plugin - Ionic 3 Labs

Don't forget to change App ID by open and edit `config.xml` then change this line.

<widget id="com.ionicfacebook" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">


3. Install and Configure Ionic 3 Native Facebook Plugin

To install Ionic 3 native Facebook plugin, type this command on the terminal or Node command line after stopping running Ionic app by press `Ctrl+C`.

ionic cordova plugin add cordova-plugin-facebook4 --variable APP_ID="YOUR_APP_ID" --variable APP_NAME="YOUR_APP_NAME"

`YOUR_APP_ID` is the App ID that you write on previous Facebook setup and `YOUR_APP_NAME` is display name on Facebook App Dashboard. Also, install `npm` module for it.

npm install --save @ionic-native/facebook

Now, open and edit `src/app/app.module.ts` then add this import.

import { Facebook } from '@ionic-native/facebook';

Also, declare in `@NgModule` providers, so it will look like this.

providers: [
  StatusBar,
  SplashScreen,
  {provide: ErrorHandler, useClass: IonicErrorHandler},
  Facebook
]


4. Implements Facebook Login and Logout

Our scenario to implements Facebook login and logout is added Facebook users in the current page if the user logged in using Facebook or show Facebook Login Button. If click on Facebook login button, it will open Facebook login on the browser. Now, open and edit `src/pages/home.ts` then add this import.

import { Facebook } from '@ionic-native/facebook';

Declare variables to check if the user logged in and holds user data before the constructor.

isLoggedIn:boolean = false;
users: any;

Inject Facebook plugin in the constructor add Facebook Connect method to check if the user is logged in.

constructor(private fb: Facebook) {
  fb.getLoginStatus()
    .then(res => {
      console.log(res.status);
      if(res.status === "connect") {
        this.isLoggedIn = true;
      } else {
        this.isLoggedIn = false;
      }
    })
    .catch(e => console.log(e));
}

Add method for Facebook login after the constructor.

login() {
  this.fb.login(['public_profile', 'user_friends', 'email'])
    .then(res => {
      if(res.status === "connected") {
        this.isLoggedIn = true;
        this.getUserDetail(res.authResponse.userID);
      } else {
        this.isLoggedIn = false;
      }
    })
    .catch(e => console.log('Error logging into Facebook', e));
}

Add Facebook logout method.

logout() {
  this.fb.logout()
    .then( res => this.isLoggedIn = false)
    .catch(e => console.log('Error logout from Facebook', e));
}

Add Facebook Graph API call method for getting user info.

getUserDetail(userid) {
  this.fb.api("/"+userid+"/?fields=id,email,name,picture,gender",["public_profile"])
    .then(res => {
      console.log(res);
      this.users = res;
    })
    .catch(e => {
      console.log(e);
    });
}

For more information about permissions and fields that returned from the response, you can check on https://developers.facebook.com/docs/facebook-login/permissions/Facebook Developer Documentation. Notes: The allowed fields based on permissions.

Next, open and edit `src/pages/home/home.html` then replace all HTML tags with this.

<ion-header>
  <ion-navbar>
    <ion-title>Home</ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <div *ngIf="isLoggedIn; else facebookLogin">
    <h2>Hi, {{users.name}} ({{users.email}})</h2>
    <p>
      Gender: {{users.gender}}
    </p>
    <p>
      <img src="{{users.picture.data.url}}" width="100" alt="{{users.name}}" />
    </p>
    <p>
      <button ion-button icon-right (click)="logout()">
        Logout
      </button>
    </p>
  </div>
  <ng-template #facebookLogin>
    <button ion-button icon-right (click)="login()">
      Login with
      <ion-icon name="logo-facebook"></ion-icon>
    </button>
  </ng-template>
</ion-content>


5. Test Ionic 3 and Facebook App on the Device

This Ionic 3 native Facebook plugin is run only on the Android or iOS device. So, prepare the Android or iOS device and connect it to your Computer using a data cable. To make sure Android or iOS platform installed correctly run this command.

ionic cordova platform rm android
ionic cordova platform add android
ionic cordova platform rm ios
ionic cordova platform add ios

Now, run the Ionic 3 Cordova Facebook app on the Device. For this tutorial, we run on Android device.

ionic cordova run android

You landing to Ionic 3 home page like this.

Login with Ionic 3 and Cordova Native Facebook Connect Plugin - Ionic 3 Facebook Android Device

Tap on the `Login with Facebook` button and you redirected to Facebook permission page then after successful login you will see the home page change to this.

Login with Ionic 3 and Cordova Native Facebook Connect Plugin - Ionic 3 Facebook Android after Login

That it's. You can test your self on the iOS device, if using simulator there will be an error after login on Facebook via the browser. If you need the source code of this tutorial, you may find on our GitHub.

Thanks!

Loading…