Login with Facebook using Ionic Framework with Example

login-with-facebook-using-ionic
login-with-facebook-using-ionic
login-with-facebook-using-ionic

Login with Facebook using Ionic Framework with Example

In this tutorial, I’m going to explain how to add “login with facebook for your ionic based applications”. 

Requirements:

  • Ionic CLI Mode
  • ngCordova
  • OAuth Plugin
  • Facebook App ID

Working : Android & iOS

OUTPUT (Language will be detected as per your loaction)

login-with-facebook-using-ionic-framework-success
login-with-facebook-using-ionic-framework-button
login-with-facebook-using-ionic-framework-success
login-with-facebook-using-ionic-framework-window
login-with-facebook-using-ionic-framework-ask-permission
login-with-facebook-using-ionic-framework-ask-permission
login-with-facebook-using-ionic-framework-success
login-with-facebook-using-ionic-framework-success

Step by step guide

Create Ionic Blank Project

ionic start LoginWithFacebook blank

Change your directory

cd LoginWithFacebook

Add your Platform

ionic platform add android

Add your plugin

ionic plugin add cordova-plugin-inappbrowser

Include Required file with your index.html (you can find with downloaded files)

<script src="js/ng-cordova.js"></script>
<script src="js/ng-cordova-oauth.min.js"></script>

Example Code (Replace with your FACEBOOK_APP_ID)

your controller

.controller('LoginwithFacebook',function($scope,$cordovaOauth){
 $scope.LoginwithFacebook = function(){
 console.log("clicked");
 $cordovaOauth.facebook("FACEBOOK_APP_ID", ["email"]).then(function(result) {
 alert("Auth Success..!!"+result);
 }, function(error) {
 alert("Auth Failed..!!"+error);
 });
 };
 });
<body ng-app="starter" ng-controller="LoginwithFacebook">
 <ion-content class="padding">
 <button class="button button-positive button-block" ng-click="LoginwithFacebook()">Login with Facebook</button>
 </ion-content>
 </body>

Download Full Example

How to create Facebook App?

Login with your Facebook developer’s account (developers) developers.facebook.com

  1. Click Create New App

login with facebook using ionic framework with example
login with facebook using ionic framework with example

2. Choose Website (www)

Choose www project
Choose www project

3. Give you Application Name & Click Create New Facebook App ID button

Give App Name
Give App Name

4. Choose your app category & Click Create App ID

Choose app category
Choose app category

5. Click Skip Quick Start

Skip this steps
Skip this steps

6. Click Settings (Left sidebar) – Basic & Fill these

App Domains : localhost

Contact Email : your Email Address

App ID: is your FACEBOO_APP_ID

Click Save Changes & Click Add Platform

fill your details
fill your details

7. Click Add Platform & Choose Website

Choose web project
Choose web project

8. Add site url as http://localhost/

Fill your email, app domain, url
Fill your email, app domain, url

9a. Choose Advanced Tab & Scroll down

choose advanced menu
choose advanced menu

9b. Add callback url http://localhost/callback & Save

Add your Redirect URL
Add your Redirect URL

 

  • islem

    Hi please can you help me i do all the step of the tutorial but i have this error

    ionic.bundle.js:25642 Error: [$injector:unpr] Unknown provider: $cordovaOauthProvider <- $cordovaOauth <- LoginwithFacebook

    http://errors.angularjs.org/1.4.3/$injector/unpr?p0=%24cordovaOauthProvider%20%3C-%20%24cordovaOauth%20%3C-%20LoginwithFacebook

    • Check These:
      1) included these files ?

      2) added angular.module(‘starter’, [‘ionic’,’ngCordova’,’ngCordovaOauth’]) ??
      3) $cordovaOauth with your controlled ?

      Feel free to download my example & try it

      • karthi

        hi help me , i followed above steps then also am getting error

        • What error ?

          • karthi

            ionic.bundle.js:26794 Error: [$injector:unpr] Unknown provider: $cordovaOauthProvider <- $cordovaOauth <- LoginwithGoogle.

  • tejashri

    please help
    after clicking login button GUI error occurs “you are not logged in.please log in and try.”

    • I don’t get your doubt clearly, may be you can try again or please provide screenshot here

      • tejashri

        after clicking on login button the below error popups and after sometime the second error popups.

  • asep furkon efendi

    thanks…it works… but after success to home page or menu page sory im beginner

    • You can used javascript page redirection

      • asep furkon efendi

        ok thank you so much senpai…
        i try..

  • karthi

    hi, any one help me i am getting this type of error
    ionic.bundle.js:26794 Error: [$injector:unpr] Unknown provider: $cordovaOauthProvider <- $cordovaOauth <- LoginwithGoogle

    • karthi

      included ,
      and
      .controller(‘LoginwithGoogle’,function($scope,$cordovaOauth){
      $scope.LoginwithGoogle = function(){
      $cordovaOauth.google(“5******************************8”, [“email”]).then(function(result) {
      alert(“Auth Success..!!”+result);
      }, function(error) {
      alert(“Auth Failed..!!”+error);
      });
      };
      })
      above is my code .its not working…

  • karthi

    hi,

    login with google everything is fine only doubt is, the functions did not return any objects

    $scope.LoginwithGoogle = function(){
    $cordovaOauth.google(“******************”, [“email”]).then(function(result) {
    alert(“Auth Success..!!”+result);
    }, function(error) {
    alert(“Auth Failed..!!”+error);
    });

  • Aini Syafinas

    hi,
    can this tutorial integrate into existing apps ?

    • Yes, you can

      • Aini Syafinas

        If i have my own controller. The controller’s code that you are given just put into mine ? i am right ?

        .controller(‘LoginwithFacebook’,function($scope,$cordovaOauth){
        $scope.LoginwithFacebook = function(){
        console.log(“clicked”);
        $cordovaOauth.facebook(“FACEBOOK_APP_ID”, [“email”]).then(function(result) {
        alert(“Auth Success..!!”+result);
        }, function(error) {
        alert(“Auth Failed..!!”+error);
        });
        };
        });

        • yes, It’s right

          • Aini Syafinas

            (function () {
            ‘use strict’;

            /**
            * @ngdoc controller
            * @name SigninCtrl
            * @module app.signin
            * @requires $rootScope
            * @requires $state
            * @requires Authentication
            * @requires $cordovaVibration
            * @description
            * Controller for the signin page.
            *
            * @ngInject
            */
            function SigninCtrl($rootScope, $state, Authentication, $cordovaVibration,$ionicHistory) {
            var vm = this;
            vm.signIn = function(credentials, isValid) {
            if(!isValid) {return;}
            Authentication.signin(credentials).then(function () {
            // save user profile details to $rootScope
            $rootScope.me = Authentication.getCurrentUser();
            $ionicHistory.clearCache();
            $ionicHistory.clearHistory();
            $ionicHistory.nextViewOptions({
            disableBack: true,
            historyRoot: true
            });
            currentUser = Authentication.getCurrentUser();
            $rootScope.$broadcast(‘user:updated’,currentUser);
            $state.go(‘app.home’, {userId: $rootScope.me._id}, { reload: true });

            }, function(error) {
            $cordovaVibration.vibrate(100);
            console.log(‘error ‘ + error);
            });
            };
            vm.goToSignup = function(){
            $state.go(‘app.signup’);
            };

            vm.goToForgetpwd = function(){
            $state.go(‘app.forgetpwd’);
            };
            }

            angular
            .module(‘app.signin’)
            .controller(‘SigninCtrl’, SigninCtrl);
            })();

            Above is my controller. So where can i put your controller’s code ? sorry im beginner 😀

  • umer safeer

    how to get user name insted of {object : object} …
    i have tried alert(JSON.stringify(userData));

    this string but it does’t show show user name it shows below array:
    {“access_token”:”EAAKahljW8BwBAGmcjkniUA1ylHyTvYMMyvZBu5YGVC5ja0sFonCPjbi1kBxkZBmhiE3AoZBhUnIanTOAewgjsydgqVZB00ZAXQ42iQffUYcArRT5a7rEYivOJHnG12rTgHXR87TSojl4fdeeWW3CuWeQ4bZCT9XZCQOGs1cUREOzAZDZD”,”expires_in”:”5173265″}

    • Read json

    • This example to user validation only. you can’t get user info, Try to use plugin for your requirement

  • Marcos Arata

    What if I already have an Oauth system using on a Website (eg example.com), how do can I set another url for http://localhost/callback on my Facebook Dev App account to work with Cordova as well?

  • elvis arce chavarria
    • I don’t know, what language is that?. can you please explain in english ? or try from step 1

  • Avi

    Not able to select website while adding Platform

    • Can you please explain your error clearly ?

  • Surya Khanal

    This way is great for login .Instead of using inapp browser to open fb login page, this is better if we can open fb app for permission.People who have fb app doesnot want to enter id password repeatedly.

  • demo test

    hello g i need help to add facebook login and google login in my ionic app, i had follow some of the tutorials, but still i confused, i got oauth id for facebook and google id. why we need use call back url like this http://localhost/callback, it is default or static call back url or else i need to create like this url in my wamp server

    • demo test

      and its show s error auth failed cannot authendicate via browser in my ionic app run on my desktop