Ionic Facebook Login and User Profile Data [v3]

ionic-facebook-login-header

Facebook login with Ionic is still one of the most requested articles, and the good news for you is: It’s not that hard at all!

In this Quick Win we will allow our user to login with his Facebook account, and after we are authenticated we make a request to grab some user information from his Facebook profile. We will have to create a new Facebook app and connect our Ionic app to that app, but you will see it takes us only a few minutes to get a result like below.

ionic-facebook-login

Note: This is the iOS behaviour and seems to be standard on that platform for some reasons. On Android, your Facebook app should open directly without those additional clicks!

Setting up a Facebook App

Before we start with our Ionic app we need a Facebook app, so go to the developer page and create a new app.

Once your app is created you need to add the iOS and Android platform. Therefore, navigate to Settings and hit + Add Platform. After adding both platforms it should look like this:

facebook-login-platforms

Notice that I already added an iOS Bundle ID and Android Google Play Package Name?

This is the next step for you, because your fields are still empty!

This is the same ID that our app has inside the config.xml file, so if you already have an app add the Id to those fields.

Otherwise, let’s create our app first and install the Facebook plugin from Ionic Native.

At this point you also need the App ID of your Facebook app as well as the name ecause they must be passed to the Cordova plugin as you can see in the statement:

If you started a new app like me, you still need to make sure that your config.xml id and the ids for iOS and Android inside your Facebook app are the same. In my case this looked like this:

Your bundle id is always your reverse domain or team name, and this is also needed when you submit your iOS or ANdroid apps later.

Now we just need to make sure that our Facebook plugin is loaded by adding it to the src/app/app.moduel.ts:

That’s all for the preparation. Actually it’s really just about creating the Facebook app, adding it with the right values to our app and adding the Platforms to the Facebook app with our id.

Simple, right?

Implementing Facebook Login

Actually the hard part is already over, now we are almost done. Inside our view we only display a button in the beginning to start our Facebook login, and once the user is logged in we display some more personal data below including the user image!

Go ahead and change your src/pages/home/home.html to:

As we have set up all before, the login with Facebook functionality is now only one line. Also, we can pass into this call which information from the user profile we want to access, in this case it is email and public_profile. Therefore, once we log in Facebook will ask for those permissions like in the image below.facebook-login-app

Once we got the login token we could e.g. login to Firebase with that token, or simply continue to make requests to the Facebook API!

We try to load a few fields from the current user which is in this case “me” and set the data from the result to our local userData variable. You can test out all the Graph API fields and calls with the Facebook Graph API Explorer!

Now to the code, replace all inside your src/pages/home/home.ts with:

Once your user is logged in, you should now see all of the data inside the view like in the image below of my profile!

facebook-login-data-received

I hope this helps you to implement Facebook login in your Ionic app, it really comes down to just a few steps and is something all modern apps have for their users!

You can find a video version of this Quick Win below.

Comments on Ionic Facebook Login and User Profile Data [v3]

  1. az26 says:

    hey simon, can i make it with firebase together? I mean in firebase there is option to make Sign in with facebook so when I do this tutorial, if I use “this auth.state” it will know if i log inlogout if i use also with firebase?

    1. Marcos Ribeiro says:

      Hey @azdir:disqus, do you having success on this integration? I need to do this too! Thanks!

  2. Michelle says:

    How do I navigate to another page after logging in with facebook?

    1. Rako Nda ᵀᴴᴱ ᴼᴿᴵᴳᴵᴻᴬᴸ says:

      if you check https://ionicframework.com/docs/native/facebook you can found the logic to do whatever you want after login.

      1. Michelle says:

        I got it working 🙂 Thanks

        1. Noel Hwande says:

          Hi. How were you able to get this to work?

          1. Michelle says:

            Hi

            Make sure you are using
            @ViewChild(Nav) nav: Nav;

            in your ts file, where you are placing the navigation code

          2. Noel Hwande says:

            Thanks very much for your help.

          3. Sanchit Mahajan says:

            Will you share your code? Thank You.

        2. Sanchit Mahajan says:

          Will you share your little code? Thank You.

  3. RhysC says:

    Awesome post Simon, I was searching around for how to get the users profile pic and this really helped. Cheers.

    Oh im also writing up a post about how to deal with the ‘account exists with different credentials’ issue with firebase if they have already signup with a username and password – will send it to you when done.

    1. beetch! says:

      Hello RhysC i am having difficulty using firebase.auth() with this example i see youve done it care to shed some light. This is what is used previously. i am retrieve first and last name to save in my firebase database

      facebookLogin(){
      this.facebook.login([‘public_profile’,’email’]).then( (response: FacebookLoginResponse) => {
      const facebookCredential = firebase.auth.FacebookAuthProvider
      .credential(response.authResponse.accessToken);

      firebase.auth().signInWithCredential(facebookCredential)
      .then((newUser) => {
      debugger
      this.userProfile.child(newUser.uid).set({
      email: newUser.email,
      points:0,
      firstName: newUser.displayName
      })

      console.log(“Firebase success: ” + JSON.stringify(newUser));
      })
      .catch((error) => {
      console.log(“Firebase failure: ” + JSON.stringify(error));
      });

      }).catch((error) => { console.log(error) });
      }

  4. SarmAd AbbaSi says:

    i have getting ‘The provided app ID does not look like a valid app ID’ error.What is the way of removing this error?

  5. supriya babar says:

    when user login with facebook, I want to store user data to the mysql database , please help me with this

    1. Bonny says:

      Have a method/function below the following (this.userData) that takes your user data object and send it to your rest api.
      this.userData = {email: profile[’email’], first_name: profile[‘first_name’], picture: profile[‘picture_large’][‘data’][‘url’], username: profile[‘name’]}

      Something like
      userService.signupWithFacebook(this.userData).then(success => console.log(‘success’)).catch(errors => console.log(errors));

      1. beetch! says:

        Hi bonny how do i use with facebook credential to log into firebase

        const facebookCredential = firebase.auth.FacebookAuthProvider
        .credential(response.authResponse.accessToken);

        firebase.auth().signInWithCredential(facebookCredential)
        .then((success) => {
        console.log(“Firebase success: ” + JSON.stringify(success));
        this.userProfile = success;

      2. JAM says:

        Thanx for this post simon.
        hey anyone help me?
        @supriya_babar:disqus I have written this code after that stored all data into nativestorage in ionic app.
        But how to stored data into mysql database? (Want same database manged for APP & Website)
        Please anyone give me solution or suggestion.

  6. Henry Vallenilla says:

    Hello, I have this error: “cordova_not_available”, What can be ?

    1. Syed M Umer says:

      Run your app on real device or emulator

    2. saidmrn says:

      or use ionic cordova run browser

  7. Subhani Shaik says:

    How about implementing Google login

    1. supriya babar says:

      I doesnot tried it.

  8. Sanchit Mahajan says:

    Thanx Sir…..

  9. Sanchit Mahajan says:

    How to divert to new page after login?

  10. amgad wagdy says:

    use this method to facebook remote logout
    http://www.townoftech.com/facebook-remote-logout/

  11. soham says:

    i tried this not working for me .i am getting this
    App Not Setup: This app is still in development mode, and you don’t have access to it. Switch to a registered test user or ask an app admin for permissions. message please help

  12. Pingback: facebook login | best hotel Delhi Hotels holiday tours homestay booking pool party
  13. Abdoulahi Dedory Fall says:

    woderful tuto.
    it only work for endroid emulator but not on real device. how to figure out?

  14. supriya babar says:

    login with facebook only work for my account ,When i try with other peoples id it does not work is gives https://uploads.disquscdn.com/images/4a2420ff693a0f403b97ece5574e11c3a980abc1e67df4bd888d1f4a1dee36ad.png Error shown in the image.Please help me. How to Remove Development Mode or add other mode.

  15. valmy roi says:

    Is it possible to store les image in database or somewhere else in the app for futher usage ?

  16. Mustafa Bekeç says:

    https://uploads.disquscdn.com/images/079db2635e4497482a4510400d1afe1a6e412f041a2723b0cc9f7daa5d1d18ba.png

    You do not have any hash keys in your training videos. How is it possible?

    I get this error when I create a Hash Key and save it in the Developer console. What is the problem ?

  17. Sanchit Mahajan says:

    In my app when i tried to login through facebook, the app name displays on facebook login page is another app name from my facebook developer profile. https://uploads.disquscdn.com/images/0381304bbc32956bd5d3d8a17d2962bedf2604c66fb2fa526d79746625b1f468.png

  18. Amir Fitri says:

    Hi, Im getting Object is not a function. Somebody know to solve it?

Leave a Reply

Your email address will not be published. Required fields are marked *