Make Your Own Facebook Mobile App With Ionic Framework

Not too long ago I contributed to the ng-cordova project on GitHub.  I added Oauth functionality to many popular API providers such as Google, Facebook, and Twitter.

I made a guide on how to use this added Oauth functionality on the official Ionic Framework blog, but since then I’ve received a good deal of requests to take it a step further and actually use on of the APIs beyond just Oauth.

This tutorial will help you better understand how to use the Facebook APIs for use in your Phonegap or Ionic Framework mobile application.

Let’s start by creating a fresh Ionic Framework Android and iOS application:

Remember, if you’re not using a Mac, you cannot add and build for the iOS platform.

There are two requirements to this project.  You must include the ngCordova library for $cordovaOauth and the Apache Cordova InAppBrowser plugin.  If you aren’t familiar with the InAppBrowser plugin, I suggest you read about it in one of my previous posts.  I also suggest you read about $cordovaOauth via the official Ionic Framework blog.

Start by installing the InAppBrowser plugin.  This can be accomplished by running the following from the Terminal or command prompt:

With the plugin installed, grab the latest ngCordova release and extract ng-cordova.min.js into your project’s www/js directory.

With the file in place, open your www/index.html file and include the library like so:

It is very important that this include goes before the cordova.js line, otherwise you’re going to get strange results.

One final thing needs to happen before we can start using ngCordova in our project.  We need to inject it into our angular.module directives.  This can be done like the following in your www/js/app.js file:

Because we like keeping things slick and easy, we’re also going to include ngStorage into our project.  More information on this library can be seen in one of my previous posts on the topic.  Download and include the library into your project.

Our Facebook project is going to be composed of the following three screens managed by the AngularJS UI-Router:

  • Login (www/templates/login.html)
  • Profile (www/templates/profile.html)
  • News feed (www/templates/feed.html)

Let’s start by adding the following code to our login template:

The only purpose the above template serves is to launch the InAppBrowser for the Oauth login flow.  The controller code can be demonstrated with the following:

Notice that after a successful login, the access token is saved and we are redirected to our profile.  The access token will be used in every future API request for the application.

Let’s take a look at the profile template.  Add the following code to your www/templates/profile.html file:

On the profile screen we will display the signed in users name, avatar, website, location, and relationship status.  There is plenty more data to choose from, but we’re keeping it simple in this example.  The controller to populate this data can be seen below:

You can see in the above code that we are making use of the /me API endpoint which is documented here.  You’ll notice that we are passing the stored access token with the request.  Without it, Facebook won’t be able to validate us.

The final screen we’ll be looking at is the news feed.  Open your www/templates/feed.html file and include the following code:

Posts to the feed will display in a similar fashion to the official Facebook application.  They will appear in one card, per post.  The controller code to go with this template can be seen below:

The feed screen makes use of the /me/feed API endpoint.  Again, we are passing the access token with the request.

 

Conclusion

Facebook has a ton of API documentation.  Unlike other services, this documentation is helpful.  This full and working project can be forked on GitHub if you’d like to see it in action.  It also includes minor bits an pieces that I’ve specifically chosen not to include in this write-up, such as the use of tabs.

Nic Raboy

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in Java, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Apache Cordova. Nic writes about his development experiences related to making web and mobile development easier to understand.

  • Tiago Winehouse

    Legal!

  • Rachid

    Thanks for the great take, but I have a question, if I want to implement a general OAuth (for example for facebook), which means users not necessarily registered an API, how can I do that ? thanks again

    • End users don’t need to register for the API. Developers need to register for the API.

      Does this answer your question?

      Regards,

      • Rachid

        Oh okay, thanks for the fast reply, I was thinking that all End users have to register for one,

        I thought it was similar solution like the one by Christophe Coenraets http://ccoenraets.github.io/ionic-tutorial/ionic-facebook-integration.html

        • Even in that plugin, only the developer needs to register for tokens. One token set per application. End users only need a username and password.

          • Rachid

            That is wierd, because everytime I try to login with different account than the developer’s one I get this error msg “App Not Setup: The developers of this app have not set up this app properly for Facebook Login.”

          • Yea I can’t speak on behalf of Christophe Coenraets, but Oauth works by using developer tokens (client id, client secret) to securely sign users in using their own accounts. Developer tokens are created per application, so you as the developer must sign into Facebook, register a new app, and then use those tokens in your code.

            I encourage you to follow along in my tutorial and see if it puts you in the right place.

            Regards,

          • Rachid

            Oh I guess I know the issue now, I have to make the “Status & reviews” ON, to enable this API for public. which I did not
            Thanks again
            Regards

          • No problem!

          • Rachid

            Oh I guess I know the issue now, I have to make the “Status & reviews” ON, to enable this API for public.
            Thanks again
            Regards

  • Oak Krittee

    vdo on youtube please. thank you.

    • I won’t be able to record new videos for a while due to a medical procedure I’m having, but I’ll take note of it when I’m able.

      • Oak Krittee

        thank you.

  • Sandor Rozsa

    Hey Mate! Great tutorial. I succeed running it fine on iOS. I am getting my profile page and also my feeds. But if i try to comment, share or if i click on the messages or like links, the initial start page with the Oauth signing appears again. My FB app is open to the public, so i am doing something obviously wrong… Help is appreciated!

  • Derrick Njenga

    Hi Nic. Am developing for android and so delighted I came across your article. But my issue comes when am trying to actually login (first interaction with the Aouth process). Am getting the error “Cannot Authenticate on a web browser” on my phone. Please help me out. Thanks in advance.

  • Martin Larochelle

    Anyone look at the Crosswalk integration in Ionic, and how to make OAuth work with Ionic+Crosswalk?

    Crosswalk and InAppBrowser are not sharing cookies, so the trick to open the InAppBrowser on top of the app then close it doesn’t get the Crosswalk based app authenticated.

    • I’ve personally not looked into this. You may want to post a generic question of Crosswalk, cookies, and InAppbrowser in the forums.

      Regards,

    • David Boling

      I use Ionic+Crosswalk on one of my apps and have ran into this issue.

      In target=_blank it doesn’t share cookies, but if you use target= _self it will share cookies. However, your popup will now close your entire app instead of just the popup. This has been a thorn in my side for the past week.

      Martin, have you by chance found any possible solution to sharing cookies between Crosswalk and InAppBrowser? Crosswalk works very well on my devices and I’d really hate to not use it due to this cookie issue.

      • Martin Larochelle

        The easiest workaround I found so far is to redirect to the hosted version of my app after the OAuth flow. This is only needed on first launch, and I don’t use Cordova plugins in this app, so other than the back button that is not working, it works pretty much seamlessly.

        I tried a couple other approaches without luck: Restarting the app, redirecting to a custom URL scheme in the hope it could start a new instance of the top activity. But none of them worked so far.

        I think the proper fix would be to make a new InAppBrowser plugin that uses the same WebView as Crosswalk. I didn’t have time to try it yet, and didn’t find an existing plugin.

  • Bunchuu

    Hi, I download your example code from here https://github.com/nraboy/ng-cordova-facebook-example. I configure the example but give me a error : Could no find InAppBrowser plugin. I made this tutorial and also gives me the same error,the plugin is installed. Im using a emulator from android studio for android and xcode emulator for ios. I would appreciate your help, thanks

    • You might try removing all the plugins and build platforms. I don’t know why this happens, but every once in a while, projects become corrupted.

      When you add everything back, make sure you add your platforms first, and then your plugins.

      Regards,

      • Bunchuu

        I did all that and it did not work ='(, also thank you for your prompt response

        • Sounds like you have a configuration issue with any of the following:

          NPM
          Ionic
          Apache Cordova
          Android Studio

          The error says it is a problem with the InAppBrowser meaning it either didn’t install, or it didn’t install correctly. You may want to post this question in the forums because it doesn’t sound like an issue with my example project or tutorial.

          Regards,

          • Bunchuu

            I install the InAppBrowser plugin with this command :
            cordova plugin add org.apache.cordova.inappbrowser
            And it worked finally =) . Thanks

          • Awesome! I’m glad you got it working 🙂

      • Thank you! That perfectly worked for me. Also i had to remove the .json files in the plugins folder or it will return an error while adding the platform.

  • Oak Krittee

    Hi,Mr.Nic, CLIENT_ID_HERE is? and how to get from? thankyou.(i am a rookie. )

    • That is the ID from your Facebook dashboard. Replace my dummy text with whatever is in your dashboard.

      Regards,

  • Prasad A U

    Hi Nic its awesome tutorial of the facebook login with $cordovaOauth.

    Is it possible to use facebook share in the above example. without the use of the $cordovaSocialSharing

    • You should check out the official Facebook API documentation. You can do pretty much anything with the right API.

      Regards,

  • Easy Esther

    May you pliiiiiiiiiiiiiz do a video tutorial for this.

    • I will see about making one as time permits. Thanks for the suggestion.

      Thanks,

  • Simon Fakir

    $localStorage is not avaible by default…

    bower install ngStorage –save

    index.html

    app dependency:
    […, ‘ngStorage’]

    • Correct. Thanks for pointing that out 🙂

    • Godwin Hottor

      Please use this instead

      bower install ngstorage

      bower install ngStorage is a different plugin that sets localstorage leys and values differently.

      https://github.com/gsklee/ngStorage

  • Ram

    How do you get ion-thumbsup to stay on/highlighted after the user has clicked it? I couldn’t find ion-thumbsup-outline and icon-on doesn’t seem to work.

    • You may want to put in an icon request with the Ionic Framework team for a filled or outlined icon. Otherwise I may recommend you use Font Awesome for your icons.

      Regards,

  • Hi Nic,

    I successfully manage to access to the facebook login form and return an access token. But for a tiny lap of time there is a white window that i manage to capture with my camera. It is saying :

    “Webpage not available
    the webpage http://localhost/callback?access_token=CAA […] 76SDAdqsd might be temporarily down or it may have moved permanently to a new web address.”

    Despite i received the access token, inside my callback function i can’t make any call to my own api right after that, which is working well outside the callback.

    http://pastebin.com/C4ZPKvQR

    Here the screenshot of my app’s settings in facebook.

    Is http://localhost/callback is right or is it something else?

    Not sure if it could be a useful information but i’m using –livereload while running the app since the last update broke my Api’s calls. I had to install cordova whitelist plugin as well to use –livereload on android. Not sure it could affect the facebook process.

  • Domantas Jurkus

    Hello, I’m having trouble running the Git example. Here’s the error I get in the console:

    Refused to load the script ‘http://192.168.0.2:35729/livereload.js?snipver=1’ because it violates the following Content Security Policy directive: “script-src ‘self’ ‘unsafe-inline’ ‘unsafe-eval'”.

  • Domantas Jurkus

    Hello, I’m having trouble running the example from Git. Followed the instructions carefully, but still got an error:

    Refused to load the script ‘http://192.168.0.2:35729/livereload.js?snipver=1’ because it violates the following Content Security Policy directive: “script-src ‘self’ ‘unsafe-inline’ ‘unsafe-eval'”.

  • haegyun jung

    Thanks for helpful post. I’m really appreciate to you!
    But I don’t understand about “localhost/callback”.
    I understand that It’s dummy url for running well this test.
    Is my thinking correct?

    • The library listens for http://localhost/callback which is why you must set it as so in the administrative dashboard. You can really set it to whatever you want, as long as the library matches.

      Regards,

  • David

    I have error with url. trying to do this tut on localhost and thats what I’ve got http://gyazo.com/3aabc627c0c049877d5d075f9dc7d385

    • Something is incorrectly configured in your Facebook dashboard.

      Possible problems:

      You didn’t make your app published / public status in the Facebook dashboard
      You didn’t add the http://localhost/callback url to the correct location of the Facebook dashboard
      You are trying to set up a native iOS or Android app when it should be web in the Facebook dashboard

      I encourage you to read through the Facebook documentation as it seems like the code is trying to function correctly.

      • David

        Thank you for advices.
        I intend to figure out what I am doing wrong. And In the meantime, can you provide your fb app settings or some example configuration of app that anyone can use for test on localhost

        • I encourage you to read the Facebook documentation:

          https://developers.facebook.com/docs/

          I’ve given the information on how to use Facebook in your application, but it is up to you when it comes to configuring Facebook to allow your application.

  • amya

    Hi there, Could you tell me the same for linkedin login in ionicframework, my code is as follows:

    $scope.Linkedin = function() {

    $scope.data = result.email-address;

    alert(JSON.stringify(result.r_emailaddress));

    • You’d have to consult the LinkedIn documentation for how to use their APIs as I don’t know. If you’re getting an error with ng-cordova-oauth, please open an issue ticket on the project’s GitHub. However, please don’t open one asking for help with the APIs, only login.

      Regards,

  • Chris

    I find it extremely irritating that the user has to enter their username and password for facebook everytime they wish to sign in to the application, the entire point of the Facebook login is to allow users one-touch access. Is there any way around this?

    — Note that while using the Facebook SDK the requirement of entering a username &| password is negated, unless the user is not signed in.

    • When using my library you’re suppose to save the access token to local storage so that way the user doesn’t have to sign in again. If you’ve already got an access token, there is no need to get one again. That is the entire purpose of oauth. I don’t demonstrate saving the access token in this example because I always leave a little to be desired on purpose in my articles.

      If you don’t like that approach you could use the native Facebook SDK, but I can tell you it is not as easy to use as my library.

      Regards,

      • Chris

        I actually took this approach, but it was still slightly annoying, the users said to just leave facebook registration out if they’d have to login the first time anyway. My point was that everyone would enjoy being able to use STSO. (Which I guess is only available through the native app?)

        Either way, your library works great. Just wasn’t exactly my cup of tea. Thanks for your response!

        • You may want to offer your feedback here after reading the GitHub thread:

          https://github.com/nraboy/ng-cordova-oauth/pull/94

          Before offering opinions about the GitHub thread, please make sure you have an understanding of both sides of the story. We’re looking for more feedback on that ticket 🙂

  • Hello Nic, how i can get email in ProfileData ? or do you have a structure graph of field /me ?

  • Anurag Pandey

    Hello , i’m using $cordovaFacebook.api its work but i not found email,gender,aboutme etc so please notify me on [email protected]

    i am using

    $cordovaFacebook.api(“me/picture?redirect=false&type=large”, [“public_profile”])

    and also use this::::

    $cordovaFacebook.api(“me/picture?redirect=false&type=large”, [“public_profile”], { params: { fields: “id,name,gender,location,website,picture,relationship_status”, format: “json” }})

    above get the photo but all other information not found;

    • I encourage you to read the Facebook API documentation. I cannot help you with the Facebook APIs as all this information is easily available to you.

      Regards,

      • Anurag Pandey

        Thanks

  • Luis Troya

    is there an alternative for iOS?

    • Ionic Framework works for Android and iOS. Are you referring to native iOS?

      Regards,

      • Luis Troya

        I ask for this “Remember, if you’re not using a Mac, you cannot add and build for the iOS platform.”

        Does not this facebook app works on iOS?

        • Yes it works for iOS, but you cannot compile iOS applications unless you are using a Mac computer. If you’re using Windows or Linux you can only build for Android. If you’re using a Mac you can build for Android and iOS.

          Regards,

  • Soumen Naskar

    Hi,

    While setting the facebook app I have to put http://localhost/callback as “Valid OAuth redirect URIs” Its fine while I am developing locally. But In production setup there is http://productionurl/ as site url, and facebook not allowing http://localhost/callback as a Valid OAuth redirect URI. So now I got stuck. As per facebook, probable solutions may be:
    1. I have to remove http://localhost/callback as “Valid OAuth redirect URI. Or
    2. make it http://productionurl/callback

    So my question is What should I do to get rid of this problem? And I have to use the appId used in production.

    Please help me out.

    • The http://localhost/callback should work fine in production. However, if you want to change it and are using the ng-cordova-oauth plugin, you can override the default redirect uri.

      $cordovaOauth.facebook(string clientId, array appScope, object options);

      For the options object you can do something like:

      {redirect_uri: “http://productionurl/callback”}

      Just make sure it matches in your Facebook dashboard.

      Regards,

      • Soumen Naskar

        Thanks, A huge thanks. I think It will solve my problem. You are the savior Nic. Let me do the change and If this thing works fine I will let you know.

        • Sounds good!

          • Soumen Naskar

            Hi Nic,

            Your first solution worked with my production setup. I just added http://localhost/callback in Valid OAuth redirect URIs field and its working fine. Anyway your second solution will also work I will use it as a backup.

            Once again A massive thanks.

          • No problem!

  • airnold

    Hi ~ now iam trying to login using facebook.. first example, in the facebook login setting method, CLIENT_ID mean facebook app id?? and how can i use facebook access token with my server generate token??

    • Server generated token? I don’t know what you’re trying to do. Maybe explain a bit more?

      Regards,

      • airnold

        now i am using nodejs server for generate json web token for user login .. so server generated token is jwt token.. i want to service custom login and facebook login..

        • I still don’t really know what you’re talking about.

          If you want your server to process Facebook login, you probably want to make a server endpoint for Facebook login and point your apps InAppBrowser to this endpoint and let your server return any information such as tokens or profile data.

          My example cuts out the need for a server.

          • airnold

            thank you for your advise !!

  • Srinivas

    Hi it is working fine for me if and only if we provide valid username and password for the first time. If you fail to give valid credentials for the first time Facebook would throw an error and then you give valid credentials it is logging into the Facebook application in InAppBrowser instead redirecting to our app. DId I miss anything. I followed your GitHub code…

    • If you didn’t accidentally click the wrong links in the InAppBrowser, it sounds like a bug in their Oauth login flow. The flow is designed to return a response, not bring you to their application.

      I’d raise a ticket with Facebook. ng-cordova-oauth follows the Oauth spec.

      Regards,

      • Srinivas

        Thanks Nic..

  • Prog MuStafa

    Please help me I’ve tried everything but I could not run the application
    Can you explain the steps for beginners please @nicraboy:disqus

    • What is the problem? I need more information in order to help you.

      Regards,

      • Prog MuStafa

        First i used facebook example But show me this message

      • Prog MuStafa

        and When I add the codes to me application nothing happens
        If you can i will send you my code and see what the problem

        • I don’t want your code because I already have it since I’m the one who wrote it 😉

          Your screenshot says you were testing it in the web browser. ng-cordova-oauth does not work in the web browser as it probably states in your logs like the alert is telling you.

          Compile the application and test it on a device or simulator. It should work then.

          Regards,

          • Prog MuStafa

            The same problem in device

          • How about sharing the logs found in the console?:

            https://www.thepolyglotdeveloper.com/2014/12/debugging-android-source-code-adb/

            Without seeing your logs there are hundreds of reasons why it might not be working. I can’t advise with that much unknown 😉

            Regards,

          • Prog MuStafa

            I’ve told you I am a beginner

            The other problem is that I am not good in English

            The only solution is to up my code on github and you see what are his problem

          • Please get your logs by following my link to another tutorial regarding ADB. When you have them, paste them in the comment of this post and we’ll go from there.

            Regards,

          • Prog MuStafa

            Thank you

          • Prog MuStafa

            I/ActivityManager( 407): Displayed com.android.systemui/.recent.RecentsActivity: +566ms

            W/IInputConnectionWrapper( 1432): showStatusIcon on inactive InputConnection

            I/qtaguid ( 407): Failed write_ctrl(s 0 10052) res=-1 errno=1

            W/NetworkManagementSocketTagger( 407): setKernelCountSet(10052, 0) failed with errno -1

            I/ActivityManager( 407): START u0 {act=com.android.systemui.recent.action.TOGGLE_RECENTS flg=0x10800000 cmp=com.android.systemui/.recent.RecentsActivity} from pid 613

            D/ ( 407): HostConnection::get() New Host Connection established 0xb98e1870, tid 1149

            D/dalvikvm( 407): GC_FOR_ALLOC freed 278K, 19% free 7607K/9360K, paused 18ms, total 19ms

            D/dalvikvm( 407): GC_FOR_ALLOC freed 250K, 21% free 7478K/9360K, paused 22ms, total 22ms

            I/qtaguid ( 407): Failed write_ctrl(s 1 10052) res=-1 errno=1

            W/NetworkManagementSocketTagger( 407): setKernelCountSet(10052, 1) failed with errno -1

            D/MobileDataStateTracker( 407): default: setPolicyDataEnable(enabled=true)

            W/EGL_genymotion( 1432): eglSurfaceAttrib not implemented

            D/dalvikvm( 1432): GC_CONCURRENT freed 456K, 23% free 4593K/5932K, paused 2ms+0ms, total 8ms

            W/EGL_genymotion( 1432): eglSurfaceAttrib not implemented

            D/PluginManager( 1432): exec() call to unknown plugin: Console

            I/Web Console( 1432): Could not find InAppBrowser plugin at file:///android_asset/www/plugins/cordova-plugin-console/www/console-via-logger.js:173

            W/InputMethodManagerService( 407): Window already focused, ignoring focus gain of: [email protected] attribute=null, token = [email protected]

            W/genymotion_audio( 128): out_write() limiting sleep time 61269 to 23219

            W/genymotion_audio( 128): out_write() limiting sleep time 52879 to 23219

            W/genymotion_audio( 128): out_write() limiting sleep time 44489 to 23219

            W/genymotion_audio( 128): out_write() limiting sleep time 36099 to 23219

            W/genymotion_audio( 128): out_write() limiting sleep time 25418 to 23219

            D/MobileDataStateTracker( 407): default: setPolicyDataEnable(enabled=true)

          • I/Web Console( 1432): Could not find InAppBrowser plugin at file:///android_asset/www/plugins/cordova-plugin-console/www/console-via-logger.js:173

            Looks like you’re didn’t install the plugin correctly.

          • Prog MuStafa

            How do I add correctly

            Regards,

          • Well, it was one of the first steps in my tutorial:

            You can also use this simplified command as well:

            Regards,

          • Prog MuStafa

            C:appmyApp>cordova plugin add https://git-wip-us.apache.org/repos/asf/cordova-plugin-inappbrowser.git

            Fetching plugin “https://git-wip-us.apache.org/repos/asf/cordova-plugin-inappbrowser.git” via git clone

            Repository “https://git-wip-us.apache.org/repos/asf/cordova-plugin-inappbrowser.git” checked out to git ref “master”.

            Plugin “cordova-plugin-inappbrowser” already installed on android.

          • Sounds like for whatever reason it might have been corrupted. It happens sometimes and I haven’t been able to figure out why. It is an Apache Cordova problem.

            Remove the plugin and try to add it again.

            Regards,

          • Prog MuStafa

            Hi Nic how are you?
            And finally the code is works

            But I have a question :
            How can we take the post on a page
            another meaning
            i can get my feed right now but i need get page feed in my app

            I wish you could have understood what I mean

            and thank you very much for Help my
            Regards,

          • Prog MuStafa

            Found a solution, a simple change
            $http.get(“https://graph.facebook.com/v2.2/{page-id}/feed”

          • michael stephenson

            I think most people are getting an SSL error on ios and they may not know how to check logs in xcode. I tried running your code after I saw how many comments this post had and I encountered the same error. When I looked at the logs I saw:

            2015-09-24 00:49:16.964 FacebookExample[40535:249175] THREAD WARNING: [‘InAppBrowser’] took ‘11.022217’ ms. Plugin should use a background thread.

            2015-09-24 00:49:17.239 FacebookExample[40535:249288] NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9802)

            2015-09-24 00:49:17.241 FacebookExample[40535:249175] webView:didFailLoadWithError – -1200: An SSL error has occurred and a secure connection to the server cannot be made.

          • Prog MuStafa

            Thank you for your response

          • Prog MuStafa

            Why the picture looks very small I want to look at full size

            I hope you help me

            Regards,

          • I don’t know the answer to that one. You should consult the Facebook APIs or the Facebook help center. The example I showed in this tutorial is as deep as my knowledge goes.

            Sorry,

          • Prog MuStafa

            Thank you for your response

            The last question to me

            How do I make my comment Likes and share button works

            Sorry for the large number of questions
            Regards,

          • Prog MuStafa

            Solve the problem of pictures that show is small
            I hope that will help other people

            {{item.story}}

          • cln

            hey, man. i too facing this issue. how did you solve this? please tell me asap!

    • Prog MuStafa

      @nicraboy:disqus Please, can you help me

      • Please don’t post numerous times like this. Consolidate your thoughts into a single comment so other commenters don’t get spammed with emails.

        Regards,

  • Jakob

    Hi, first of all thanks a lot for the tutorial. I got the Facebook login to work with my ionic app. 🙂

    I got one question left though: After the initial login, do you know what’s best practice for handling future requests from the app to a user’s facebook? Let’s say the user wants to update his profile every now and then, using facebook data. How do I handle those requests? I read the access token expires within 2 hours?

    • After you obtain the access token you should store it along with the current time plus 60 minutes. Every time your users try to use the application you should do a check to see if the current time equals the stored expiration time. If the token is not expired, bypass login because you still have a working access token. If the token is expired, then prompt with the oauth flow again.

      In terms of updating the user profile, you need to read the Facebook RESTful API documentation as I cannot help you there. I was really just demonstrating how to log in and get basic information to prove that it worked.

      Regards,

      • Jakob

        sounds good to me, thanks again!

  • Brian

    Hi Nic, I have already commented one of your post few days ago about uploading images. I still have that problem with IOS 9 and the new Xcode that you mentioned, but for now I gave up on it, I will try to see if it work directly on device.

    I wanted to thank you and congratulate for your amazing tutorial, they are really helping me out developing my first IONIC app.

    However, I am again stuck on some issue, and this time is Facebook integration 🙁

    I am trying to run my app on IOS, implemented only your login controller first, and after few changes:

    removed whitelist
    added transport security

    The facebook page finally showed! But… I now have this error: Given URL is not allowed by the Application configuration: One or more of the given URL is not allowed 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.

    My configuration on Facebook Settings are:
    a) Added a Website platform with as URL the address of my Azure Web API (e.g. https://microsoft-apiapp7a…… .net)
    b) Validated e-mail address and opened the FB app publicly
    c) Since I am running from Cordova, I’ve added as valid OAuth URLs https://www.facebook.com/connect/login_success.html
    d) Tried to enable embedded Browser OAuth login, but didn’t work

    Can you help on this please? I believe I am missing some little detail that I can’t see and it is keeping me stuck for days already!

    • Brian

      Forget it! For anybody who’s trying this, check Nic’s GitHub!

      The trick was using: http://localhost/callback as valid OAuth URL in Facebook Settings! 😀

  • Prog MuStafa

    Hi Nic
    how to open the profile with $ionicmodal ??

    • Prog MuStafa

      Why do not you answer my questions ???

      • Heres the deal.

        I get many questions every day and often don’t have time to answer them right away because of course I have a life outside of the blog. Since I don’t charge any money, I do things on my schedule.

        Your comment was rather rude, so I suggest you don’t make comments like that. If you don’t like the speed of my responses I suggest you ask your questions somewhere else instead.

        That aside, the $ionicModal is not very relevant to the points I was trying to prove in this tutorial. The point was to show that it is possible to use the Facebook RESTful API in your application.

        Regards,

        • mt_nasty

          LOLing at this guy not reading documentation that is available to everyone for free…… You’re way nicer than I would have been, @nicraboy:disqus. Thanks for all the great articles. You’ve really sped up my Ionic development about ten-fold!!!

          • No problem, I’m glad I was able to help you in a positive way!

            It is a bit frustrating when I offer my help for free and get ungrateful responses from people who think they are entitled to receive a premium service.

            That’s the 21st century for you I guess.

  • Gonzoide

    Hi Nic,

    First of all, kudos for this wonderful plugin, I was able to integrate it in a matter of minutes in my ionic project.

    I’m new to the whole Facebook world though, so I probably missed something trivial that prevents the inAppBrowser from succeeding (but issue is definitely on the Facebook side) : I used the appId provided by Facebook, on Facebook app page I created a new Android app and specified my package, but I still get this infamous error 191 : The specified URL is not owned by the application

    By any chance, would you have any pointers about how to configure App on Facebook side so that it accepts requests from my app running on android real device ? Thanks

    • Gonzoide

      Extra info after a few tests : APP_ID is correct, my app was built in release, signed, and key hashes match (as well as package name), Facebook app is public.

      I must be missing something trivial, because it seems all I did is an overkill and many people can directly connect from a debug session on real device ???

      • Sounds like configuration issues in your Facebook dashboard. Make sure you are using Facebook for web applications and that you have the correct URL in the Oauth Redirect Callback section. You won’t need a secret key.

        If you’re using Android you can use ADB to debug your application from a real device.

        Best,

        • Gonzoide

          Actually I found out what the problem was : I didn’t get this configuration of “localhost” used by many, I thought they were using this configuration for web app development, so I discarded this information a little bit too quickly :).

          Indeed I added “http://localhost:8100/” both as a website URL and as OAuth redirect URI, works as a charm 🙂 Maybe it would be worth mentioning in your (otherwise perfect) article : app side is well documented, but this Facebook trick is a little bit more difficult to find.

          Thanks again for this excellent plugin.

          • No problem! Glad you got it working 🙂

  • cooknick

    Hey Nic, great stuff, I’ve been searching for a long time for something like this. However, I can’t get passed the login credentials. After logging in, it redirects me to a facebook error page that says “The page you requested cannot be displayed right now. It may be temporarily unavailable, the link you clicked on may be broken or expired, or you may not have permission to view this page”. And it won’t redirect out of the InAppBrowser. Any Ideas? Thanks in advanced.

    • What do your logs say?

      • cooknick

        This error occurs in Ionic View, and I’m not sure how to see the log output when using Ionic View. On the iOS Sim, it wont open Facebook because it can’t find the InAppBrowser (according to the log there). I’ve tried reinstalling the InAppBrowser but it still won’t be recognized by the sim.

        • You cannot do oauth with Ionic View, Ionic Serve, or Ionic Live-Reload.

          Best,

          • cooknick

            That would explain why it’s not returning to the app in Ionic View. Any ideas on why the InAppBrowser works in Ionic View but not the sim? Or does that fall under the umbrella of Live-Reload (even when I don’t run the emulate command with livereload)

          • I don’t ever recommend using ionic view, ionic live reload, or ionic serve. These are not good ways to test your application. Stop bad habits early.

            In regards to the simulator, I assume you probably have errors in your logs. What do they say?

            Regards,

          • cooknick

            It says “Could not find InAppBrowser plugin”. I’ve removed and re-added the platform and plugin and got the same results.

          • There is a bug with Apache Cordova 5.4.0. I’m working on a fix. If you don’t want to wait for a fix, downgrade your Apache Cordova to 5.3.3.

            Regards,

  • anurag_arora

    I am able to login to Facebook and get back access_token , but when making angular $http request for viewing profile page, if throws error:
    $http request code:

    var url = “https://graph.facebook.com/meaccess_token=” + $localStorage.accessToken;
    $http({
    method: ‘GET’,
    url: url
    }).then(function successCallback(response) {
    alert(“success”);
    alert(JSON.stringify(response.data));
    }, function errorCallback(response) {
    alert(“error”);
    alert(JSON.stringify(response));
    });

    above code works properly in plnkr and postman but throws error in android emulator:
    error:
    “{“data”:””,”status”:404,”config”:{“method”:”GET”,”transformRequest”:[null],”transformResponse”:[null],”url”:”https://graph.facebook.com/me?access_token=*****”,”headers”:{“Accept”:”application/json, text/plain, /”}},”statusText”:”Not Found”}”,

  • Ramesh Yadav

    Without App Secret it is opening a page saying you are not loggedin which is blank and no login form is there

    • Facebook uses implicit grants so no client secret is needed. My guess is that you’ve configured something incorrectly in your Facebook Developer Dashboard.

      What do your actual logs say?

      Regards,

      • Ramesh Yadav

        In the backed we are using omnioauth which is working fine as it take client id and client secret both but on mobile I’m having this issue

        • Server side uses explicit grants which requires both a client id and a client secret. Client side uses implicit grants which only requires a client id.

          I encourage you to read up on oauth 2.0 so you know what you’re getting yourself into.

          I cannot help you further without seeing your logs.

          Best,

  • Magnus Burton
    • The http://localhost:8100 in your logs leads me to believe you’re using ionic serve, ionic live reload, or ionic view. None of these are compatible when using ng-cordova-oauth.

      However, the error you received doesn’t appear to be related. I believe you have a typo somewhere or you’ve forgotten to include the JS file in the correct location of your index.html. You also want to make sure you’re using ngCordovaOauth, not ngCordova.

      In regards to http://localhost:8100 if you don’t stop using one of those ionic services you’re going to run into a mess of problems later.

      Regards,

  • Jessica Thompson

    will this work with firebase instead of local storage?

    • I don’t know why you would want to

  • bruno

    Hello Nic
    Firstly, Thank you soo much for this tutorial. I am having some trouble in running in this app.
    I am new to mobile/hybrid apps. I followed all the steps. and run this app in genymotion emulator. when app gets open.. There is a button for Oauth sign. When I click on that button it says “Not logged in: You are not logged in. Please login and try.”. I entered client id in app.js file. Can you please help me.
    Thanks

    • This means you didn’t add the oauth callback correctly in the Facebook dashboard.

  • sandeep tyagi

    Hey Nic, this is a really helpful post. Can you please help me getting the user feed as i am getting error with the read_stream.

  • Mayank S. Gupta

    First thing. facebook default app permission are public_profile, email, user_friends. I am getting this error CONSOLE(49)] “Facebook returned error_code=100: Invalid permissions”, source: file:///android_asset/www/js/app.js (49) error used everything correct. just added permission email,public_profile. Even tried by just changing app id . Does not works.

    • Can you tell me if my GitHub example works for you?

      • Mayank S. Gupta

        no not working. thats error Iam getting

      • Mayank S. Gupta

        I got it working. Just removed v2.0 from oauth url.

  • ishara withanage

    It worked Nic , A great tutorial i really appreciate your effort.. May u get the much strength to post more valuable tutorials like this

    • Thanks for the compliment!

      • ishara withanage

        Dear Nic, i was looking forward for functionalities like post facebook via this app and share or comment,
        is OpenFB a good solution?

        • This tutorial was only intended to get you started. For other Facebook functionality I suggest reading about the rest of the official APIs.

          Best,

  • Dheeraj Singal

    Hi Nic, I know this post is old, but getting an error on login attempt. When I serve to a browser I see this error: Unknown provider: $cordovaOauthProvider <- $cordovaOauth <- LoginController. I was considering downloading the ng-cordova-oauth.js file but saw you did not have in your git project. Thanks for your assistance.

    • You might try downloading the latest ng-cordova-oauth dist if trying to run the github project.

  • Abhi Kureshi

    i have an error how can i fix it please help for this

  • Abhi Kureshi

    can you give me new code for make facebook app. i cant access it.

    • I encourage you to look at the example I put on GitHub as well as review the Facebook APIs.

      • Abhi Kureshi

        thanks nic

      • Abhi Kureshi

        please send me particular link of this.

      • Abhi Kureshi

        thanks nic

      • Abhi Kureshi

        I am making one app project. while i add function of social share in this app then it is not working but while i create new project then it is working well. i dnt know what is the error. my project is based on IT JOBS. I implemented many features in this app. many libraries included. i think because of this reason this is cant working. do you guess what error??

      • Abhi Kureshi

        my code is

        app.controller(‘Social’, function ($scope) {

        //
        $scope.share = function (t, msg, img, link) {

        })

        i also implement plugin “cordova plugin add cordova-plugin-x-socialsharing”

        in controller js “var app = angular.module(‘starter.controllers’, [‘ionic’, ‘ngCordova’, ‘starter.services’])”

        in app.js “var app = angular.module(‘starter’, [‘ionic’,’starter.controllers’, ‘starter.services’, ‘ngCordova’, ‘starter.services’, ‘morphCarousel’, ‘ionic.ion.headerShrink’, ‘ionic-ratings’])

  • Shaktisinh Parmar

    Any One help me!!! I’m just beginner in ionic. My problem is how I’m checking user is logged in app or not, if user logged not display login page & redirect to dashboard. Give Solution……..

  • Shaktisinh Parmar

    Any One send me link,where the best resources are available….

  • shan

    So the user logged in through facebook and access the app but if the user wants to login next time, should he go through the same process again?

    • In this example the token is saved to local storage. Unless it has expired, the user will not have to log in again.

  • Amit Batra

    hey nic is it possible to access the user’s phone number using access token?

    • If the Facebook API has an endpoint that includes the phone number, sure. You’d have to read the Facebook documentation.

  • Amit Batra

    Thanx Nic,read the whole documentation,Facebook removed that feature few months ago due to user’s privacy ..

    • Yep, unfortunately that is out of our control

  • James

    When I tried emulating this on an Android device using Android Studio, it keeps giving me an error whenever I click on the login button:

    ReferenceError: facebookConnectPlugin is not defined

    I thought this error would only pop up if you try running the app on the browser. What am I doing wrong here please?

  • James

    Not sure why but I thought the $cordovaOauth.facebook(ID, [param]) method should also return the data specified in the parameters (such as email, name, gender, etc.). However when I inspect the contents of the result object that is returned, I only find the access_token and exp_date as keys. I had to invoke an $http.get to retrieve the data. What am I doing wrong please? Thanks.

    • It is not the job of oauth to return API data. It is only for requesting permission to use the APIs, thus it will take an array of permissions and return an access token. With the access token you can use it for any APIs that you’ve requested access to.

      Does this clear things up?

      • James

        Yes thank you, very much so!

  • Chaiya Louer

    Hello Nic, I have problem after login done it doesn’t redirect back to my profile page.

    • What does it do instead? What do your logs say? I need a lot more information to help you out.

      https://www.thepolyglotdeveloper.com/2015/10/how-to-get-programming-help-in-forums-and-on-my-blog/

      Regards,

      • Chaiya Louer

        Sorry Nic, I don’t have log file. Log file auto generate or I need create log file manually?

      • Chaiya Louer

        Sorry Nic, I don’t have log file. what should I do to have log file.
        And this is my redirect_uri like this {redirect_uri: “http://localhost:8100/#/app/profile”}.

        • You cannot use URLs like that as a callback. Must be an absolute URL, not one that uses a partial like “#/app/profile”. You also cannot use ports in your URL.

          I encourage you to read up on the oauth specification.

          Best,

          • Chaiya Louer

            yes thank Nic, now I can see my profile page. I would like to ask you one more question “how to keep facebook logging even we close app.”

            Regard,

          • Store the access token and expiration in local storage. When the app starts up, if the token is expired or doesn’t exist, prompt to sign in

          • Chaiya Louer

            thank you Nic, I got akey.

  • andreyshedko

    Hi Nic!
    This all working just prefectly. I suppose that this plugin available for authorization purposes only? Is that right? If yes, could you advise please what to use for work with Facebook Api, I understand that I can use pure JS or Angular but may be there is some other ng-cordova plugins exist for these purposes?
    P.S. Guys who’s blaiming that InAppBrowser plugin is not working, please make sure first that all loaded correctly, all injections made and libraries linked in your index.html

    • There may be libraries, but the REST API really isn’t that bad.

  • cln

    hi Nic,
    I was trying this tutorial. that was very useful. But i could not loggedin to facebook. some error saying, ‘invalid scopes: read_stream…’

  • cln

    hey nic, can you please add logout function
    @Nic Raboy

    • Just remove the access token from storage and you’ll be logged out.

      Best,

  • cln

    hey nic, how do i get the user_likes in my app?

    • You’d have to consult the official Facebook API documentation.

      Best,

  • noor

    Can you please help me, I keep getting this error : Cannot set property ‘accessToken’ of undefined. How do I fix this?

  • noor

    How can I set a custom redirect_uri in the options ?

    • $cordovaOauth.facebook(“CLIENT_ID_HERE”, [scopes…], {redirect_uri: “http://somesite.com/callback”})?

  • Med Dhaker Abdeljawed

    Hi, when i login it redirect to a facebook page which says : Sorry; somthing went wrong and a go back button which redirect to fb login page, I’am using an android Device for test, any help ?

    • Sounds like your app is incorrectly configured in the Facebook dashboard.

  • Marcos Arata

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

    • You can set multiple callback URLs for an app in the Facebook dashboard.

      • Marcos Arata

        Hi Nic, thanks a lot! So I just need to add on Facebook Login tab inside field “Valid OAuth redirect URIs” the http://localhost/callback“? I also tried to add on Settings>Basic field “App Domains” but it doesn’t allow me to set localhost as a domain as it doesn’t match with my Website Site URL (example.com).