Use ng2-cordova-oauth For All Your Ionic 2 Oauth Needs

Previously I wrote about using Oauth within an Ionic 2 mobile application.  However, for the typical user that can be a real hassle because it by far isn’t short.  This is why I created the library ng2-cordova-oauth on GitHub.  This library has numerous web service providers bundled in, making the authentication flow as short as three lines of code.

Now some of you might be familiar with the ng-cordova-oauth library that I wrote for Ionic Framework 1.  That library was designed to work with Apache Cordova and AngularJS.  This time around I did the same thing for Angular 2 and Apache Cordova.

Let’s take a look at how easy this new library really is.

Before I start, let me start by saying that ng2-cordova-oauth works great for Angular 2 JavaScript and Angular 2 TypeScript applications.  You have the freedom of choice on how to use it!  Let me also state that this library will not work in your web browser and it probably won’t work with Ionic Serve or Ionic View.  The reason for this is that these services alter how the application runs, which isn’t good for us.  If you know me, you know that I avoid the web browser, Ionic Serve, and Ionic View like the plague.

With that out of the way, let’s create a new project.  From the Command Prompt (Windows) or Terminal (Mac and Linux), execute the following commands:

A few important things to note.  First, you must be using the Ionic CLI that supports Ionic 2.  Second you must be using a Mac if you want to add and build for the iOS platform.

Next up, our application relies on the Apache Cordova InAppBrowser.  It can be added like the following:

Finally we need to install the ng2-cordova-oauth library.  To install this library, execute the following from the Terminal or Command Prompt, with the project as your current working directory:

We can now start coding!

We’ll be spending all our time in two files.  The app/pages/home/home.html file will contain our UI and the app/pages/home/home.ts file will contain our logic.

Let’s start with the UI file.  Open app/pages/home/home.html and change it to the following:

Essentially we have a screen with a button on it.  When the button is clicked, the login() function is executed.  This function will be found in our logic file.

Now open your project’s app/pages/home/home.ts file and change it to the following:

First we are importing the appropriate classes.  Inside the constructor we initialize the CordovaOauth object to use Facebook and pass in the configuration options.

When the login() function is executed we first make sure the app is ready.  This is necessary when trying to use Apache Cordova plugins to prevent errors.  When the app is ready, we call login, which is asynchronous.  When the flow finishes or fails, we’ll know about it.

In case you’re wondering where the clientId came from, it is from the Facebook Developer Dashboard.  In order to use Facebook, like most providers, you’ll need to configure an app with them.

Conclusion

We saw how to manually design authentication workflows, but the simpler and recommended way would be to use the ng2-cordova-oauth library that I created.  This Angular 2 library is similar to my AngularJS wrapper, but now works for Angular 2 JavaScript and Angular 2 TypeScript.  Just to be clear, this library works with providers beyond Facebook.

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.

  • sramesh

    Thanks Nic, this looks really useful. I was curious if you have an example to do simple login using email ?

    • Simple / basic login using an email and password is very different from oauth. Web services use oauth for secure login and token distribution which can then be used towards their APIs.

      • sramesh

        Thank for the quick reply. Ugh !! What was I thinking ? Sorry 🙂 I have been trying too get the firebase email/pwd style to work with ionic2 and though this would too. Well, your blog is a great early resource for ionic2, which I am loving and I am very early into it. But keep

        up the blogs coming 🙂 Thanks again.

  • Arturo Santamaría

    Hi, i’m new using Ionic Framework and i’m trying to implement the oauth login, but i have some questions:

    1.- Where do i get/save information like the username, userID, profile image, e-mail etc. because i want to save this information in a database and i need it to display that information in my profile.html template.

    2.- I wonder if this process works for Ionic Framework 1 because when I started my new app i didn’t add the “–v2” tag after the name of the template i’m using.

    Thanks a lot Nic for all your effort. This is not the first time I’m learning from you.

    Thank you for your attention and forgive my English.

    • Hey @arturosantamara:disqus,

      To answer your questions:

      That information comes from the APIs that you wish to use. Oauth is only a form of authentication and doesn’t directly get data about the service you’re trying to use. With the access token returned from the oauth protocol, you can use the available APIs (Facebook, etc.) to get any information you need.
      I have two different versions of this library. This in particular is for –v2 of Ionic. If you want –v1 you can find it here. https://github.com/nraboy/ng-cordova-oauth

      Best,

  • aluknot

    This can be acomplished with firebase without problem right?

    • I don’t use Firebase any more so I don’t know. Sorry.

  • usman rehman

    this example is platform (ios, android) dependent? I mean will it work on the browser? because i’m unable to run it on my browser using simple “ionic serve”

    • The 4th paragraph says this:

      “… Let me also state that this library will not work in your web browser and it probably won’t work with Ionic Serve or Ionic View. The reason for this is that these services alter how the application runs, which isn’t good for us. If you know me, you know that I avoid the web browser, Ionic Serve, and Ionic View like the plague.”

      Best,

      • usman rehman

        Now i know you 🙂

      • usman rehman

        Nic, Unable to run it on android. I just generated APK file and install it on android mobile. it show me nothing except blank screen. can you please help me?

        • What do your logs say?

          • usman rehman

            I think not able to generate the Build.js using “gulp build”
            I have tried gulp build and it says you have an error. on line 9 which is

            constructor(platform: Platform)

            I think app is not able to find the platform as you have added the platform using this

            import {Page, Platform} from ‘ionic/ionic’;

            and there is no such folder in node_modules with name “ionic”. so, it seems like app is not able to locate the ionic.js to add platfrom and page.

            what do you say?

            have you seen any issue at your side?

          • usman rehman

            exact error:

            SyntaxError: C:/wamp/www/ionic/ExampleFB/app/pages/home/home.js: Unexpected token (9:24) while parsing file: C:wampwwwionicExampleFBapppageshomehome.js

            and line 9 is constructor(platform: Platform)

            I have added the android platform

          • I apologize for my late response. I’ve updated the code to make use of the latest Ionic 2 beta.

            I tested it and it works flawlessly.

            Best,

          • usman rehman

            thanks nic.
            do you know about nav.PopTo ??
            how can we use it?

          • Sounds unrelated to this topic. You might created a request here:

            https://www.thepolyglotdeveloper.com/2015/07/what-programming-tutorials-do-you-want-to-see/

            Best,

          • usman rehman

            posted Nic

  • Nuno Arruda

    Thanks @nicraboy:disqus for this plugin, since at the moment I cannot use the Ionic Authentication service because it’s not ready for v2 yet, I will temporarily use your plugin in the Ionic 2 app I’m currently developing. Not being able to use ionic serve or Ionic View to test the authentication is a huge inconvenience for me because I no longer have an easy way to show the app to the client. Anyone knows any alternative that allows me to use ionic serve/Ionic view?

  • Nuno Arruda

    How about logging out the user? How to do that?

    • Remove the access token from storage. No access token equals no login.

      Best,

  • Famous

    Nic would this work with the WordPress API to log users into their accounts on a multi user install?

    • It’s WordPress supported currently? No, but could it be? Absolutely.

      I do want to get WordPress working in the future.

  • Jeremy Lan

    Hello Nic, How can we use this library for any other services like, trackTV API?

  • Tony

    Hi Nic, I am trying to find the list of “appScope” to see if I can request more than email, do you have it by any chance ? I have been looking with no luck.. Thank you lots !

  • Moeed Nisar

    Nice Tutorial. i have successfully implemented the facebook login. but the success object returns only access token and expires in time, i need to get the user info from their profile (e.g. Name, Age, DOB, email etc) could you please help me to get this info???

    1 more thing is it possible to get the login authentication via native app using this plugin

    Thanks

    • To answer your first concern, oauth will only ever return tokens. This is true for all providers, not just Facebook. You need to read the API documentation for each provider on how to use the tokens to get useful information.

      To answer your second concern, this plugin is sandboxed and will never work with other plugins or apps.

  • Abhijeet Kesarkar

    i tried to implement that and i get error “You are not logged in, please log in and try again” on my device and console.log shows
    The Facebook sign in flow was canceled

    • That error means you’ve incorrectly configured something in the Facebook dashboard. I encourage you to read their developer documentation.

    • Ali Makeen

      it’s a common error. It occurs because you haven’t added http://localhost/callback to OAuth redirect URIs in the configuration of your FB app.

  • Shu Lin

    Hi Nic, Thanks a lot for providing this package. This really make our code clean and give us the chance more focusing on our real app instead of oauth logic. But, one thing we noticed is the user has to re-input his username every time while the inapp browser is brought up for the authentication. Is there a way to save the username just as normal browser behavior? Thanks!

    • Save the access token and add some conditional logic so the application does not log in if the token exists and is not expired.

      • Shu Lin

        Yes. We can do that. But, there will still be nice even after the login expires, the user doesn’t need reenter the username. The normal browser can give this. Can we achieve this feature here? Thanks.

        • Please open a feature request ticket on the github project.

          Best,

  • Ionic Facebook

    i got used for thids code

    but

    error :;- undefine this.platfrom

    • I just updated this tutorial to use TypeScript and the latest version of Ionic 2. I tested and everything works fine now.

      Best,

  • Zülfü Çakmak

    Hey Nic, I’m trying to add ng2-cordova-oauth plugin. But doesnt install. There is no error log. How can i fix this. I updated cordova to latest version. When I run app

    Typescript Error
    Module ‘”/Users/zulfucakmak/ExampleProject/node_modules/ng2-cordova-oauth/core”‘ has no exported member ‘CordovaOauth’.

    this error appears.

    • The plugin changed a bit. Please review the README on GitHub