November 7, 2014
  • All
  • Ionic

OAuth with Ionic and ngCordova

Nic Raboy

This is a guest post by Nic Ra...

This is a guest post by Nic Raboy, an application developer with a strong background in Android, AngularJS, Ionic, Java, SQL, and Unity3D. Nic writes often about Ionic and how to build great hybrid apps.

I get a lot of inquiries regarding OAuth 2.0 with Apache Cordova and Ionic Framework applications. Although I do have another post elaborating on how to accomplish this, I decided to take it a step further and make a simplistic library for AngularJS.

I created ngCordovaOauth, which can be found on GitHub. It was designed to make it as simple as possible to obtain access tokens for some of the popular web APIs, such as Google.

I took my ngCordovaOauth library a step further, and included it in the official ngCordova project. For the sake of this tutorial, I’m going to explain things around the official ngCordova library which is now the official implementation.

When I was designing the OAuth functionality, my strategy was to expect a promise based on the login flow. If the flow is successful, we will receive an object containing whatever the server responds with. Otherwise, we’ll get some kind of error.

Although I designed this with Ionic Framework in mind, it will also work for any Apache Cordova or Phonegap application that makes use of AngularJS. With this in mind, let’s set up the library for use.

ionic start IonicProject blank
cd IonicProject
ionic platform add android
ionic platform add ios

Note that if you are not using a Mac, you cannot build for iOS.

OAuth with ngCordova relies heavily on the Apache Cordova InAppBrowser plugin. If you’d like to know more about how this plugin works, you can view my previous post on the topic, otherwise just continue by running the following:

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

Your Ionic project is now ready for the ngCordova library. Download it and include ng-cordova.min.js into your www/js directory.

Open the www/index.html file and include the following:

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

One more item must be added in order to fully make use of this plugin. You must inject ngCordova into your AngularJS module found in the www/js/app.js file:

angular.module('starter', ['ionic', 'ngCordova'])

Here is an example of how you might use the OAuth with the ngCordova library:

var ionicExample = angular.module('starter', ['ionic', 'ngCordova']);

ionicExample.controller("OauthExample", function($scope, $cordovaOauth) {

    $scope.googleLogin = function() {
        $cordovaOauth.google("CLIENT_ID_HERE", ["https://www.googleapis.com/auth/urlshortener", "https://www.googleapis.com/auth/userinfo.email"]).then(function(result) {
            console.log(JSON.stringify(result));
        }, function(error) {
            console.log(error);
        });
    }

});

As of right now, the following methods are available:

$cordovaOauth.dropbox(string appKey);
$cordovaOauth.digitalOcean(string clientId, string clientSecret);
$cordovaOauth.google(string clientId, array appScope);
$cordovaOauth.github(string clientId, string clientSecret, array appScope);
$cordovaOauth.facebook(string clientId, array appScope);
$cordovaOauth.linkedin(string clientId, string clientSecret, array appScope, string state);
$cordovaOauth.instagram(string clientId, array appScope);
$cordovaOauth.box(string clientId, string clientSecret, string state);

There are some things to note about OAuth with ngCordova:

  • It will only work on your device or simulator. It will not work in the web browser.
  • All redirect / callback URIs must point to http://localhost/callback; otherwise, the login flow will not complete.

When you have your access token, you can typically make full use of the web APIs for that service. For example, if you wanted to use one of the Digital Ocean APIs, you might do the following:

var ionicExample = angular.module('starter', ['ionic', 'ngCordova']);

ionicExample.controller("DigitalOceanExample", function($scope, $http, $cordovaOauth) {

    $scope.digitalOceanLogin = function() {
        $cordovaOauth.digitalOcean("CLIENT_ID_HERE", "CLIENT_SECRET_HERE").then(function(result) {
            window.localStorage.setItem("access_token", result.access_token);
        }, function(error) {
            console.log(error);
        });
    }

    $scope.getDroplets = function() {
        $http.defaults.headers.common.Authorization = "Bearer " + window.localStorage.getItem("access_token");
        $http.get("https://api.digitalocean.com/v2/droplets")
            .success(function(data) {
                console.log(JSON.stringify(data.droplets));
            })
            .error(function(error) {
                console.log(error);
            });
    }

});

Notice that in the above example, we are using the access token. In this particular example, the access token is used in the header, but in many APIs, the access token is passed in the POST or GET parameters.

Conclusion

Adding OAuth to your Ionic apps is easy with the new OAuth support in ngCordova. With support for such providers as Google, Facebook, and Dropbox, it’s just a matter of adding your authentication tokens and linking with the plugin.

Support for Twitter, which uses a slightly different client-side token system, is coming soon!


Nic Raboy

This is a guest post by Nic Ra...