Mobile
Article

How to Integrate Facebook Login into a Cordova Based App

By Narayan Prusty

If your App needs Login or Registration functionality, then using 3rd party services such as Facebook Authentication are useful tools to utilize.

This tutorial is for developers using Cordova with jQuery Mobile for UI and ngCordovaOauth to add Facebook login functionality. The app will enable users to login via Facebook and then display their basic profile information. The primary motive of this tutorial is to show how to implement Facebook login in Cordova apps and how to use ngCordovaOauth in non-Ionic or non-AngularJS UI based app.

How does OAuth Authentication Work?

The OAuth protocol is an authentication mechanism used by many web services (such as Facebook, Twitter and LinkedIn) to provide user information to third party apps.

According to the OAuth protocol, the user should be first redirected to the web service by the third party app. The user then grants permission to an app and an access token is generated that is returned to the third party app. The access token acts like a permission to access user information.

What is ngCordova and ngCordovaOauth?

ngCordova is a collection of 63+ AngularJS modules. Some are wrappers for Cordova plugins and others are wrappers for pure JavaScript libraries. ngCordovaOauth is one of the ngCordova modules.

ngCordovaOauth is a JavaScript library wrapped within an AngularJS module. The purpose of this library is to obtain an access token from a web service to use their APIs and access user information.

I will be using ngCordovaOauth because it works on all platforms and supports additional web services that can be implemented using the same methods as the Facebook login implementation.

Creating a Facebook Developer App

Every third party app that integrates Facebook login needs to create a Facebook developer app. A developer app helps Facebook track the third party app and provides additional configuration options.

To create a Facebook developer app for our Cordova app do the following:

Visit the Facebook Developer Apps Page and click Add a New App. Select Website as the platform.

Adding a new App to Facebook

Enter an app name and click Create new Facebook App ID.

Add App Name

Select your app category and click Create App ID.

Create App ID

Click Skip Quick Start in the top right corner.

Skip Quick Start

Enter the app domain and Site URL into the Basic settings tab as shown below

App Domain and Site URL

Under the Advanced tab add the redirect OAuth URL as shown below.

OAuth URL

Creating a Cordova App

To create my app template I need to include jQuery mobile and ngCordovaOauth with their dependencies. I won’t cover installing and creating a Cordova Application here, if you haven’t done this before, read this getting started guide. Instructions to run and build the application are available on the same page.

Give the Application an appropriate name and add the supported platforms. I am using Cordova’s InAppBrowser plugin in this tutorial, you can find instructions here on adding plugins here.

You can find the final code of this project on gitHub.

Inside the www/index.html file, add the following JavaScript and CSS files in the head tag. These are the jQuery Mobile and ngCordovaOauth loaded from CDNs. You should embed these files locally so that the app works without an Internet connection.

<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">

<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>

<script src="http://code.ionicframework.com/nightly/js/ionic.bundle.js"></script>
<script src="https://cdn.rawgit.com/driftyco/ng-cordova/master/dist/ng-cordova.min.js"></script>
<script src="https://cdn.rawgit.com/nraboy/ng-cordova-oauth/master/dist/ng-cordova-oauth.min.js"></script>

<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="cordova_plugins.js"></script>

Creating the Home Screen

The home screen of our app will display a button instructing the user to login via Facebook. When the user clicks the button the user will be redirected to Facebook.

Create a AngularJS app using the ng-app directive and a controller using the ng-controller directive. Place this code inside the body tag of www/index.html replacing the divs that are currently there:

<div ng-app="facebookApp">
    <div ng-controller="mainCtrl">
    </div>
</div>

Now create the home screen. Place this code inside the body tag of the www/index.html file below the code we just added:

<div data-role="page" id="home">
    <div data-role="header">
        <h1>Login</h1>
      </div>

      <div data-role="main" class="ui-content">
        <p>You need to login to view your Facebook profile information</p>
        <a target="_blank" href="#" onclick="login()" style="text-decoration: none"><button>Login using Facebook</button></a>
      </div>
</div>

This is how the home screen should now look:

Current home screen

Creating the Profile Screen

Once the user gives access to the app, display the user profile information. Here is the code for the profile page, place this code below the home screen page:

<div data-role="page" id="profile">
    <div data-role="header">
        <a target="_blank" href="#home" class="ui-btn ui-icon-home ui-btn-icon-left">Home</a>
        <h1>Profile</h1>
    </div>
    <div data-role="main" class="ui-content" id="listTable"></div>
</div>

Implementing Facebook Login

To initiate the AngularJS app we need to get a reference of the ngCordovaOauth methods for the Facebook login. Place this code inside a script tag before the closing body tag in the www/index.html page:

angular.module("facebookApp", ["ionic", "ngCordova"]).controller("mainCtrl", ["$scope", "$cordovaOauth", "$http", function($scope, $cordovaOauth, $http) {
    window.cordovaOauth = $cordovaOauth;
    window.http = $http;
}]);

Here the AngularJS app is initiated and then loads the necessary modules to use ngCordovaOauth. Then the reference to the ngCordovaOauth and http module is saved globally.

When the login button is clicked, the login method is invoked and the login method calls the facebookLogin function. facebookLogin is a custom function which redirects to the Facebook website. Place this code in the script tag created previously:

function login()
{
    facebookLogin(window.cordovaOauth, window.http);
}

function facebookLogin($cordovaOauth, $http)
{
    $cordovaOauth.facebook("1633195863589792", ["email", "public_profile"], {redirect_uri: "http://localhost/callback"}).then(function(result){
        displayData($http, result.access_token);
    },  function(error){
            alert("Error: " + error);
    });
}

The $cordovaOauth.facebook() method requires several parameters:
1. APP ID: The ID of the facebook developer app. This is found on the dashboard of the app.
2. Permissions: These are for accessing information about the user. A complete list of permissions can be found on the Facebook permissions page.

The $cordovaOauth.facebook() method returns a promise object. Once the user has given access to our app, the displayData function is called that makes a Graph API request to retrieve a range of information about the user.

Here is the displayData function, which should be placed in the script tag created above:

function displayData($http, access_token)
{
    $http.get("https://graph.facebook.com/v2.2/me", {params: {access_token: access_token, fields: "name,gender,location,picture", format: "json" }}).then(function(result) {
        var name = result.data.name;
        var gender = result.data.gender;
        var picture = result.data.picture;

        var html = '<table id="table" data-role="table" data-mode="column" class="ui-responsive"><thead><tr><th>Field</th><th>Info</th></tr></thead><tbody>';
        html = html + "<tr><td>" + "Name" + "</td><td>" + name + "</td></tr>";
        html = html + "<tr><td>" + "Gender" + "</td><td>" + gender + "</td></tr>";
        html = html + "<tr><td>" + "Picture" + "</td><td><img src='" + picture.data.url + "' /></td></tr>";

        html = html + "</tbody></table>";

        document.getElementById("listTable").innerHTML = html;
        $.mobile.changePage($("#profile"), "slide", true, true);
    }, function(error) {
        alert("Error: " + error);
    });
}

Here a Graph API request is made to retrieve the user’s name, profile picture and gender. While making Graph API requests the access token is needed. Then a responsive jQuery mobile table is created and added to the profile page content.

Here is how the profile page should now look:

Profile page

Conclusion

This app shows developers how to implement a Facebook login in Cordova apps and how to use ngCordovaOauth in non-Ionic or non-AngularJS UI based apps. Currently the app is functional, but basic and can be deployed to multiple platforms. The next steps are displaying more information and letting users post or change their profile picture.

Let me know your experiences trying this tutorial and ideas for expanding it.

More:
  • http://julienrenaux.fr/ Julien Renaux

    good stuff, I suggest to use http://ngcordova.com/docs/plugins/facebook/ instead, services are already created there is no need for $http and they return promises.

  • Pius Ngugi

    Great post! One concern, After login in facebook, the call back is called but with a 404 how can I be able to surpass that and get back to my applicaiton

  • YS Tsang

    you are doing all anti-angular pattern.

    • http://www.wiziwiz.com/ wiziwiz

      anti-angular what?

  • Pravin Vanmore

    where are this two files on your repository. If not will you please make it available?
    thanks in advance

    • byte

      Hi, sorry for the late answer: Cordova.js is a phantom library which gets created automatically when building the project, it doesn’t exist physically. If you get the error message that cordova.js is missing, you will have to convert your “HTML5 web app” into a “Cordova HTML5 web app”. Most of development environments like Intel XDK offer that option in the project settings.

  • http://www.iziuse.com Reza Rahmati

    Great Article, what we need to store for the next time the user runs the app to keep him logged in. I mean now every time the user runs the app he needs to login and give permission, what we can do to keep him logged in.

    • Nikhil Indurkar

      I have one concern..
      In my case only login is asked as per permission concerns only first time it had been asked to me..
      Is it happening in your case..
      Please update..
      Thanks in andvance Reza..

  • Nikhil Indurkar

    Great Article..I think i am very close to use this..one error i am getting is like
    “Given URL is not permitted by the application configuration:One or more of the given URLs is not permitted by the App’s settings. It must match the Website URL or Canvas URL, or the domain must be a subdomain of one of the App’s domains”

    and another concern is how do I get back to my application.

    • Nikhil Indurkar

      For this i found the solution is I have add App Domain and required configuration said in this bolg. :)

    • Nikhil Indurkar

      For this i found the solution is I have add App Domain and required configuration said in this bolg. :)

  • Nikhil Indurkar

    Excellent post..It is working fine for me..
    Thanks a ton man.

  • Nikhil Indurkar

    Excellent post..It is working fine for me..
    Thanks a ton man.

  • Nikhil Indurkar

    Hey Narayan,
    Can you please tell me what other details we can access from facebook and what parameter needed to pass for display..
    Thanks in advance

  • Ankit balyan

    How will i set default language to english, its taking my regional language by default,, i tried adding local=en_US param as well, but didn’t worked.

  • sameer

    I have an error, which is Error:Cannot authenticate via a web browser, what can i do?

  • Benhur Tessaro

    i have an error, You are not logged : You not connected to Facebook . Come in and try again.

    • Ary Teruel Domenech

      I have the same error. Did you find a solution? Thanks

  • http://www.mondodigitale.com masai2k

    It’s all ok, when I try to login the facebook login appears (with email and pass login), but I would know how to connect with facebook in background.
    I mean, if I have the facebook application on my device, usually other apps login with facebook without ask my my email and password, but ‘simply’ take them from facebook app …. How can I do that with ng-cordova???

  • tejashri

    error for $cordovaOauth.facebook as “cannot read property ‘facebook’

  • Eduardo Adams Wohlfahrt

    You really do a great job! sitepoint been an important source of research on my cordova projects, this and other items as ReminderApp and PushNotification were actually many useful for me! Thank you very much!

  • shan

    Thank you for such an article. But I am confused about one thing. I think that if a user signup with facebook then s/he should login through facebook not from the app login. Is it not true? If it is then was the above tutorial for signup or login?

  • Chaiya Louer

    redirect_uri: “http://localhost/callback”}.
    how can I redirect back to profile page after login done?

Recommended

Learn Coding Online
Learn Web Development

Start learning web development and design for free with SitePoint Premium!

Get the latest in Mobile, once a week, for free.