Using An Oauth 2.0 Service Within An Ionic 2 Mobile App

Previously I demonstrated how to use Oauth in an Ionic Framework 1 Android and iOS mobile application, but with Ionic 2 becoming all the rage, I figured my old guide needed a refresher.

Modern applications are always making use of APIs and data from third party services.  The problem is, these remote services require a special kind of authentication to happen in order to work with the data they manage.  The most common form of authentication for web services is Oauth.

In my Ionic Framework 1 tutorial I demonstrated Google Oauth, but this time we’re going to see how to use Facebook Oauth in an Ionic 2 application.

As you probably know already, Ionic 2 uses Angular 2.  To best understand what we’re doing, it is best to make a fresh Ionic 2 application.  From the Command Prompt (Windows) or Terminal (Mac and Linux), execute the following commands:

It is important to note that you must be using the Ionic CLI that supports Ionic 2.  You must also be using a Mac if you wish to add and build for the iOS platform.

We’re going to be using a mobile web browser for the authentication flow.  This means we’ll need to have the Apache Cordova InAppBrowser plugin installed.  From your Terminal or Command Prompt with the project as your current directory, execute the following:

Before we start looking at code, we need to create a Facebook application.  This can be done for free from the Facebook Developer Dashboard.  During this creation process you want to make sure the Valid Oauth redirect URIs is set to http://localhost/callback.  This setting can be found in the Facebook Dashboard’s Settings -> Advanced tab.

Take note of the App ID of your Facebook application.  This is also known as a Client ID and it will be used within the Ionic 2 application.

With that out of the way, let’s code!

Open your project’s app/pages/home/home.html file and change it to look like the following:

The above snippet is our UI.  It contains only one button which will start the authentication flow.  This is done through a login() function that we’re going to create now.

Open your project’s app/pages/home/home.ts file and change it to look like the following:

There are two functions here.  Since the authentication flow is an asynchronous process I figured it would be easiest to split it from our button call.  In other words, login() will call the facebookLogin() function.

However, before going there, notice the line near the top that reads:

We are using an Apache Cordova plugin that has no TypeScript type definitions.  If we don’t declare this important object as any, we’ll get errors during the build phase.  Now we can look at the functions.

Starting with the login() function, add the following:

In the above function we first make sure the app is ready.  This is a requirement before trying to use Apache Cordova plugins.  We know that facebookLogin() is asynchronous so we wait for a success or error event to happen and show a message appropriately.

This is where the complicated stuff comes in.  Take a look at the following facebookLogin() function, then we’ll break it down:

First off, notice that we’re wrapping the whole thing in a Promise.  When we’re finished and we know login was a success we’ll call the resolve and if there is an error or bail out for any reason we’ll call the reject.

Now notice the following line:

We’re launching the InAppBrowser plugin and keeping reference of it so that way we can inspect it whenever we want.  The URL launched is the required endpoint per the Facebook documentation.  If you’re using a different provider, you’d change it as necessary.

Since we have the browser reference we can look at the current page every time it loads.  This is done through the loadstart event like so:

If the current page starts with http://localhost/callback like set as our redirect URI in the Facebook Dashboard, it means we’ve finished signing in and our access token is attached.  We just need to parse the token out now.

The access token exists in the URL so the remainder of our code is just parsing it out and returning it successfully as an object to the user.

Ionic 2 Oauth Flow 1 Ionic 2 Oauth Flow 2 Ionic 2 Oauth Flow 3

Above are some screenshots of what the Facebook Oauth flow might look like in the app we just made.

Conclusion

We just saw how to initiate a Facebook Oauth authentication flow in an Ionic 2 Android and iOS mobile application.  It is a step up from our previous Ionic Framework 1 example.  We saw how to use the Apache Cordova InAppBrowser plugin and monitor its events to process Facebook login which is an implicit grant flow.  In all honesty, you can just use the ng2-cordova-oauth plugin I made to accomplish this stuff, but I’ll have another article on that subject.

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.

  • C.H

    There has no app/pages/home/home.html in ionic project directionary.

    • Update your Ionic CLI to the latest beta release. You’re using an older version 😉

      • C.H

        It’s OK, Thanks.

  • Gregor

    Hi @nicraboy:disqus. Thank you for this tutorial. I’m trying to bind my inappbrowser to handle the twitter connection. Sadly, their API is so bad I can’t even start with simple URL which I would call with my Twitter APP key so the user would then grant access to APP itself. Can you help me out please?

    Thank you and kind regards!

    • Twitter uses Oauth 1.0A where as this tutorial uses Oauth 2.0. They are two very different forms of Oauth.

      • Gregor

        And maybe that’s also the reason, they request token at authorization state, which means, you have to request token first with your app credentials, then you can send user to the “approval” page. Quite a different procedure.

        Thank you 🙂

        • Laura Jacobsen

          @Gregor did you get this working with Twitter? I want to authenticate Flickr, which uses OAuth 1.0, in an Ionic app.

  • Piccaza

    Hi Nic 🙂

    I have tried out exactly as you described here, everything worked as expected.
    Still, got some more doubts on how can I use this access token to get user Id, email, profile informations in my app?

  • Fernando

    Oye gracias por los tutoriales
    Queria pedirte un favor:

    Es quiero enviar una imagen en base64 de ionic2 a un servio pero cuando envio la IMAGE me pone este error
    “21 413008 error Fallido [object Object]”

    es un http.put()

  • Paulinho Junior

    Great tutorial Nic, tks! Hey, with firebase is much different?

    • I don’t know. I stopped using Firebase a long time ago.

  • sharedOne

    Hi, Thanks for the tutorial. It really helped me out a lot. Do you also have a tutorial on how to work with the access token (store it locally so users don’t have to authenticate again the next time, store data to server, ask for new authorization token if it expires) or do you know of any other tutorials about this. Because I’m really not sure how I should do that. Thanks again.

  • Shu Lin

    Hi, I got below error while I use this code.

    How should I solve this problem? Thanks!

    • Are you using ‘window’ or are you using ‘Window’? Also are you trying to use ionic serve, ionic live-reload, or ionic view? None of those are compatible.

      • Shu Lin

        Nic, Thanks for your reply. I know what I was wrong. I was trying to copy your code piece in typescript .ts file. I was creating the ionic project with “–ts” option. Do you know how i can use cordova feature in typescript? I did install cordova plugins. I think I am missing the way how to refer the cordova interface defined in typings.

  • Ritesh Bhat

    ERROR
    when running in my device the app shows error
    like this
    ERROR
    You are not logged in: You are not logged in. Please log in and try again.

    • Marwane SEBBAR

      the same probleme

  • Lokesh Sahu

    I got following error
    TS2339: Property ‘cordova’ does not exist on type ‘Window’

  • Ionic Facebook

    ionic run android for my app but property cordova does not exist on type window

  • Ionic v2

    follow you step ,but can’t alert to access token then login() ..

    • Etinosa Akenuwa

      this is because linkden does not return the access token but linkden returns a value called the code, check out their docs https://developer.linkedin.com/docs/oauth2, so in the code replace [“access_token”] with [“code”] @ line 13 for the facebookLogin() function

  • Shu Lin

    Nic,
    Have you seen this article? What will be the solution for Ionic oauth after Google change this?
    https://developers.googleblog.com/2016/08/modernizing-oauth-interactions-in-native-apps.html
    Thanks.

    • Yes I’ve seen it. When Google no longer supports the web view, you’ll have to use their native SDK if you wish to authenticated with their APIs. It is unfortunate, but Google is big enough to do whatever they want.

  • Amarjit Singh

    how can i authentication with hotmail (ionic)? have you any working code or tutorial plz share.