Monaca Docs
  • Monaca
  • Create Your First App
  • Release Notes and Updates
    • Privacy Manifest Requirement for iOS Apps
    • Plugin uses-permission Tag Deduplication Feature
    • iOS Monaca Debugger Discontinuation & Alternative Features
    • Error submitting to iOS App Store (ITMS-90165)
    • Build error in cordova-custom-config
    • Cordova 11 changes
    • Cordova 10 changes
    • Cordova 9 changes
    • New Monaca CLI and Localkit
    • Migration from Cordova to Capacitor
  • Product Guides
    • Monaca Development Overview
    • Monaca Cloud IDE
      • Overview
      • Features in the Monaca Cloud IDE
      • Integrated Terminal
      • Editor Shortcuts
      • Project Dependencies
        • File and Folder Structure
        • JS/CSS Components
        • Cordova Plugins
        • Custom Cordova Plugins
      • Version Control
        • Introduction
        • GitHub Integration
        • Git SSH Integration
      • Monaca CI
        • Overview
        • Deploy Services
        • Deploy to Appetize.io
        • Deploy to DeployGate
        • Deploy to Firebase
      • Build
        • Building for iOS
          • Building an iOS App
          • Build Settings between Monaca and Xcode
        • Building for Android
        • Building for Electron
          • Building on Windows
        • Building for PWA
        • Building for Windows
        • Build Environment Settings
        • Common Build and Application Upload Errors
        • Build History
      • Distribution
        • App Store Distribution
          • App Store Connect Guide
          • iOS App Upload Feature
        • Google Play Distribution
        • Amazon Appstore Distribution
        • Non-market App Distribution
      • Download App Package
      • Tutorial
    • Monaca Localkit
      • Overview
      • Pairing and Debugging
      • Remote Building and Publishing
      • Troubleshooting Guide
      • Tutorial
    • Monaca CLI
      • Overview
      • Monaca CLI Commands
      • Pairing and Debugging
      • Project Dependencies
        • File and Folder Structure
        • JS/JSS Components
        • Cordova Plugins
        • Custom Cordova Plugins
      • Remote Building and Publishing
      • Troubleshooting Guide
      • Tutorial
    • Monaca Debugger
      • Functionalities
      • Installation
        • Monaca Debugger for Android
        • Monaca Debugger for iOS
        • Monaca Debugger for Android Emulator
      • Usage
      • Custom Build Debugger for iOS
      • iOS App Simulator Build
      • Troubleshooting Guide
      • Tutorials
    • Team Dashboard
    • Quick Viewer
    • Migrating from Other Platforms
      • Key Points
      • Cloud IDE preview function settings
      • Migrating from Angular
      • Migrating from Ionic
      • Migrating from React
      • Migrating from Vue
      • Migrating from PhoneGap
        • Key Differences
        • Guide for PhoneGap Build Users
        • Guide for PhoneGap CLI Users
        • Guide for PhoneGap Desktop App Users
      • Migrating from Telerik
  • Build App
    • Build for iOS
      • Creating a Private Key and CSR
      • Creating a Certificate
      • Updating Provisioning Profiles
  • Tutorials
    • Monaca Cloud IDE Tutorial
      • Part 1: Starting a Project
      • Part 2: Running Monaca Debugger with Monaca Cloud IDE
      • Part 3: Building a Monaca App
      • Part 4: Publishing a Monaca App
    • Monaca Localkit Tutorial
      • Part 1: Starting a Project
      • Part 2: Running Monaca Debugger with Monaca Localkit
      • Part 3: Building a Monaca App
      • Part 4: Publishing a Monaca App
    • Monaca CLI Tutorial
      • Part 1: Starting a Project
      • Part 2: Running Monaca Debugger with Monaca CLI
      • Part 3: Building a Monaca App
      • Part 4: Publishing a Monaca App
    • Electron Tutorial
      • How to Use a NPM Package
      • How to Use a Web API
    • Barcode Scanner Plugin
    • Cordova SQLite Storage Plugin
    • Cordova Google Analytics Plugin
    • Cordova Firebase Plugin
    • Cordova In-app Purchase Plugin
    • Cordova AppVersion Plugin
    • Cordova Ionic Keyboard Plugin
    • Cordova Social Sharing Plugin
    • NIFCLOUD mobile backend
    • Phonegap Push Plugin
  • API Reference
    • Monaca API
      • Monaca Cloud & Remote Build API Guide
      • Utilities
    • Core Cordova Plugins
      • Cordova 11.0
        • Battery Status Plugin
        • Camera Plugin
        • Device Plugin
        • Device Motion Plugin
        • Device Orientation Plugin
        • Dialogs Plugin
        • File Plugin
        • Geolocation Plugin
        • InAppBrowser Plugin
        • Media Plugin
        • Media Capture Plugin
        • Network Information Plugin
        • Splashscreen Plugin
        • Vibration Plugin
        • StatusBar Plugin
      • Cordova 10.0
        • Battery Status Plugin
        • Camera Plugin
        • Device Plugin
        • Device Motion Plugin
        • Device Orientation Plugin
        • Dialogs Plugin
        • File Plugin
        • Geolocation Plugin
        • InAppBrowser Plugin
        • Media Plugin
        • Media Capture Plugin
        • Network Information Plugin
        • Splashscreen Plugin
        • Vibration Plugin
        • StatusBar Plugin
        • Whitelist Plugin (Android Only)
      • Cordova 9.0
        • Battery Status Plugin
        • Camera Plugin
        • Contacts Plugin
        • Device Plugin
        • Device Motion Plugin
        • Device Orientation Plugin
        • Dialogs Plugin
        • File Plugin
        • File Transfer Plugin
        • Geolocation Plugin
        • Globalization Plugin
        • InAppBrowser Plugin
        • Media Plugin
        • Media Capture Plugin
        • Network Information Plugin
        • Splashscreen Plugin
        • Vibration Plugin
        • StatusBar Plugin
        • Whitelist Plugin (Android Only)
    • Third-party Cordova Plugins
      • Advanced HTTP Plugin
      • PhoneGap BarcodeScanner Plugin
      • Cordova Custom Config Plugin
      • DatePicker Plugin
      • Share Plugin (Android)
      • WebIntent Plugin (Android)
    • Monaca Power Plugins
      • Monaca HTML5 Resource Encryption
      • Monaca In-App Updater
      • Monaca Secure Storage
      • Barcode Scanner Plugin
      • Android build memory size setting
    • Service Integration
      • Repro
      • AppsFlyer
    • Configuration Files
      • Android
        • Android Configuration
        • config.xml
        • AndroidManifest.xml
      • iOS
        • iOS Configuration
        • config.xml
        • MonacaApp-Info.plist
  • Samples & Tips
    • Sample Apps
      • AdMob
      • Twitter Single Sign-on App
      • Facebook Single Sign-on App
      • Flickr
      • TODO App
      • BirthYear App
      • Break the Bricks
      • Train Catalog App
      • Omikuji Fortune Telling App
      • Clock App
      • Memo Application
      • RSS Reader App
      • Hello World App
    • Tips & Tricks
      • Playing Sound and Music
      • Control the Splash Screen
      • Using Database
  • Features
    • Push Notification
    • SNS Authentication
    • Database
  • FAQ
    • General
    • IDE
    • Build
    • Release
    • Subscription
      • How to Use Activation Code
    • Application
    • Usage
    • Debugger
  • Supported Environments
  • Trouble Shooting
    • Preview Log repeats to reload (Vue packages version mismatch error)
  • Monaca Product Website
  • 日本語
Powered by GitBook
On this page
  • Demo
  • Prerequisite
  • Importing the Project to Monaca Cloud IDE
  • Configuring the Plugin
  • Application Explanation
  • File Components
  • HTML Explanation
  • Stylesheet Explanation
  • JavaScript Explanation

Was this helpful?

  1. Samples & Tips
  2. Sample Apps

Facebook Single Sign-on App

PreviousTwitter Single Sign-on AppNextFlickr

Last updated 3 years ago

Was this helpful?

In this page, you will learn how to use Facebook's Single Sign-On (SSO) with Monaca Cloud IDE using Angular 1 and . The authentication is done by . This plugin will use the native Facebook app to perform Single Sign On for the user; otherwise, the sign on will degrade gracefully using the standard dialog based authentication.

  • To check third party cordova plugins, you need to create a custom build debugger ( or

  • The following settings are required in config.xml.

<platform name="android">     <preference name="android-minSdkVersion" value="22"/> </platform>

Demo

Tested Environment

  • Android 11.0

  • iOS 14.3

Prerequisite

APP_ID and APP_NAME are required by the cordova-plugin-facebook4 plugin. These two values can be found in the Facebook for Developer console after registering your app. To do so, please proceed as follows:

  1. Go to My Apps → Add a New App.

3. Input the necessary information of your app and click Create App ID.

4. From the Dashboard, go to Settings and you will be able to find the APP_ID (App ID) and APP_NAME (Display Name).

5. Now it’s time to add the platform(s) of the devices which will run your app by clicking + Add Platform button.

6. If your app will run on Android, select Android.

7. Fill in the necessary information as shown below and click Save Changes :

  • Google Play Package Name: is the Android’s Package Name you configured in Monaca Cloud IDE for Android App Settings.

  • Enable Single Sign On option.

8. If your app will run on iOS as well, Click + Add Platform and select iOS.

9. Fill in the necessary information as shown below and Save Changes :

  • Bundle ID: is the iOS’s App ID you configured in Monaca Cloud IDE for iOS App Settings.

  • Enable Single Sign On option.

Importing the Project to Monaca Cloud IDE

Configuring the Plugin

Before starting to use the plugin, you are required to input the APP_ID and APP_NAME values within the plugin’s configuration as follows:

  1. From Monaca Cloud IDE menu, go to Configure → Cordova Plugin Settings.

  2. Under the Enabled Plugins section, hover over cordova-plugin-facebook4 and click Configure button.

4. Click OK to complete the configuration.

Application Explanation

File Components

File

Description

index.html

The startup Page

home.html

Login Page

profile.html

User profile Page

css/style.css

A stylesheet file for the application

js/app.js

A JavaScript file for implementation of the application

HTML Explanation

index.html

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<meta http-equiv="Content-Security-Policy" content="default-src * data:; style-src * 'unsafe-inline'; script-src * 'unsafe-inline' 'unsafe-eval'">
<script src="components/loader.js"></script>
<script src="lib/angular/angular.min.js"></script>
<script src="lib/onsenui/js/onsenui.min.js"></script>
<script src="lib/onsenui/js/angular-onsenui.min.js"></script>
<script src="js/app.js"></script>

<link rel="stylesheet" href="components/loader.css">
<link rel="stylesheet" href="lib/onsenui/css/onsenui.css">
<link rel="stylesheet" href="lib/onsenui/css/onsen-css-components.css">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
  <body >
      <ons-navigator id="myNavigator" page="home.html"></ons-navigator>
  </body>
</body>
</html>

home.html

<ons-page ng-controller="HomeCtrl">
  <ons-toolbar>
      <div class="center">Facebook Demo</div>
  </ons-toolbar>
  <div class="page">
      <p class="center">
          Welcome to Facebook Authentication Demo with Monaca using Onsen UI and AngularJS!
      </p>
      <ons-button ng-click="Login()">
          Connect to Facebook
      </ons-button>
  </div>
</ons-page>

This page is a login page. If there is existing login information found in the device, it will be automatically redirected to profile.html page.

profile.html

<ons-page ng-controller="ProfileCtrl">
  <ons-toolbar>
      <div class="center">Facebook Profile</div>
      <div class="right">
          <ons-toolbar-button ng-click="Logout()">
              <ons-icon icon="fa-sign-out"></ons-icon>
          </ons-toolbar-button>
      </div>
  </ons-toolbar>
  <div class="page">
      <p class="center">
          <img src="{{user.profile_url}}" class="profile">
          <p>{{user.name}}</p>
          <p>(@{{user.id}})</p>
          <p>{{user.email}}</p>
      </p>
  </div>
</ons-page>

This page is a user's Facebook profile page.

Stylesheet Explanation

This file consists of the CSS style for the navigation bar and Facebook profile image.

div.page {
 padding: 5%;
 text-align: center;
}

p.center {
  text-align: center;
}

img.profile {
  width: 40%;
  border: solid 1px #1da1f2;
  border-radius: 5px;
}

.navigation-bar {
  background-color: #4267b2;
}

.button {
  background-color: #4267b2;
}

JavaScript Explanation

ons.bootstrap()
.service('StorageService', function() {
  var setLoginUser = function(user_info) {
      window.localStorage.login_user = JSON.stringify(user_info);
  };

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

  return {
      getLoginUser: getLoginUser,
      setLoginUser: setLoginUser
  };
})

.controller('HomeCtrl', function($scope, StorageService, $http, $q) {
  var CheckLoginStatus = function(){
      window.facebookConnectPlugin.getLoginStatus(
          function(data){
              if(data.authResponse){
                  console.log('Login info is found!');
                  myNavigator.pushPage('profile.html');
              }else{
                  console.log('No login info is found!');
              }
          },
          function(e){
              LoginError(e);
          }
      );
  }

  ons.ready(function() {
      CheckLoginStatus();
  });

  var GetProfileInfo = function (authResponse) {
      var info = $q.defer();

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

  var LoginSuccess = function(response){
      var authResponse = response.authResponse;

      GetProfileInfo(authResponse).then(function(user) {
          StorageService.setLoginUser({
              name: user.name,
              id: user.id,
              email: user.email,
              profile_url: "http://graph.facebook.com/" + authResponse.userID + "/picture?type=large"
          });
          myNavigator.pushPage('profile.html');
      }, function(error){
          console.log('Error retrieving user profile' + JSON.stringify(error));
      });

  };

  var LoginError = function(error){
      console.log('Login Error: ' + JSON.stringify(error));
      // When "User cancelled dialog" error appears
      if (error.errorCode === "4201"){
          CheckLoginStatus();
      }
  };

  $scope.Login = function(){
      facebookConnectPlugin.login(['email', 'public_profile'], LoginSuccess, LoginError);
  }


})
.controller('ProfileCtrl', function($scope, StorageService, $http, $q) {
  $scope.user = StorageService.getLoginUser();

  var LogoutFromFacebook = function(){
      facebookConnectPlugin.logout(
          function() {
              console.log('Successful logout!');
              myNavigator.pushPage("home.html");
          },
          function(error) {
              console.log('Error logging out: ' + JSON.stringify(error));
          }
      );
  }

  $scope.Logout = function(){
      ons.notification.confirm({
          message: "Are you sure you want to log out?",
          title: 'Facebook Demo',
          buttonLabels: ["Yes", "No"],
          callback: function(idx) {
          switch (idx) {
              case 0:
                  LogoutFromFacebook();
              case 1:
                  break;
              break;
          }
        }
      });
  }
});

Inside this file, there is a service, called StorageService, to store the login information of the user using the device's Local Storage. There are also two controllers such as HomeCtrl and ProfileCtrl which are the controllers for home.html and profile.html pages, respectively.

HomeCtrl controller consists of several functions used within the home.html page. Once, the page is loaded, the CheckLoginStatus() function is triggered to check if there is any existing login information. If the login information is found, the myNavigator.pushPage() function is called to navigate to profile.html page showing the user's Facebook profile as found in the login information. When the user clicks on Connect to Facebook button, the Login() function is triggered. In this function, the facebookConnectPlugin.login() function is called to show the native Facebook authentication dialog. If the login is successful, the login information will be stored in the device's local storage via StorageService.setLoginUser() function and then the myNavigator.pushPage() function is called to navigate to profile.html page.

If you have logged in with a Facebook app on your device, the information of that account will be automatically grabbed and used in this app. If you want to login with a different account, please go to your Facebook app and change the account there.

However, if you do not have a Facebook app on your device or you have not logged in the existing Facebook app on your device, the authentication screen will appear:

In the ProfileCtrl controller, there are 2 functions: Logout() and LogoutFromFacebook(). The Logout() function is called when the user clicks on the Logout icon on the top-right corner of the Profile page. Inside the Logout() function, a confirmation dialog is shown. If the user selects Yes, both LogoutFromFacebook() function StorageService service are called to log the user out and remove the login information from the device's local storage, respectively.

Go to and log in with your Facebook account.

Key Hashes: is the SHA-1 fingerprint of the KeyStore you configured in Monaca Cloud IDE for Android KeyStore Settings. Please refer to .

The authentication is done by . This plugin will use the native Facebook app to perform Single Sign-on for the user; otherwise, the sign on will degrade gracefully using the standard dialog based authentication.

3. Input the APP_ID and APP_NAME values you got in the section. See the screenshot below as an example:

This file is the startup page of the application. As you can see within the <body> tag, there is only one component. It provides page stack management and navigation. The attribute page is used to identify the first page in the stack.

Facebook for Developers
Import Facebook Single Sign-on App to your Monaca Account
cordova-plugin-facebook4
ons-navigator
Prerequisite
Onsen UI
cordova-plugin-facebook4
Import Facebook Single Sign-on App to your Monaca Account
How to get SHA-1 fingerprint of a keystore created in Monaca Cloud IDE
Android version
iOS version