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!

75 Comments

  • For the FB Oauth, line 4965 should be

    if(cordovaMetadata.hasOwnProperty(“cordova-plugin-inappbrowser”) === true) {

    I’m using 0.1.12-alpha.

  • Avatar Melih says:

    For DigitalOcean, I’m getting this error:

    “Cannot authenticate via a web browser”

    On :

    $scope.digitalOceanLogin = function() {
    $cordovaOauth.digitalOcean(client_id, client_secret).then(function(result) {
    window.localStorage.setItem(“access_token”, result.access_token);
    }, function(error) {
    console.log(error);
    });
    }

  • Avatar Aaron Hillel Swartz says:

    I have some doubts regarding the Facebook auth, what is the ‘CLIENT_ID’? is it the Facebook App ID or what ? and what is the http://localhost/callback ? should be the route where the user goes after login ? I did not get that part, sorry. I am new.

    • Avatar Brayan Mayk Castro Pacheco says:

      Client id is the id of your facebook app, and the localhost/callback is the url callback to set up in your facebook app

  • Avatar Tyler Harrington says:

    For the salesforce login I am getting: Error -> Could not find InAppBrowser plugin

    However the plugin was added successfully and I can see when I run $ cordova plugin list

    Am I missing something?

  • Avatar Alejandro Jose Ortiz Larquin says:

    Hi, I’m new with Oauth and I’m trying to get the facebook user’s mail so I put [“email”] in my scope but what I am getting is an access token and a expire date instead of the info I want. Do I need to implement any other step?

  • Avatar Gustavo Reyes says:

    How would I do it if I have my own provider, let’s say Django Oauth Provider and I want to use the credentials of my django app?

  • Avatar Cristhian Molina says:

    hello me is returning this error in console Can not authenticate via a web browser

    • Avatar Adil Mourahi says:


      It will only work on your device or simulator. It will not work in the web browser.”

  • Avatar Manvick Paliwal says:

    I have created a working example of ngcordova Oauth plugin.
    You can check it here
    http://ngcordova-outh.blogspot.in/

    • Avatar Joy Choudhary says:

      fraud if you have knowledge then make a twitter based oauth ionic sample app. you just put basic things on the above mentioned link…..

  • Avatar Anil Kumar says:

    Hi Nic,

    I followed the above tutorial it is working fine , but I need some requirements like to access the basic profile info of the user I have used https://www.googleapis.com/auth/userinfo.profile in app scope it is accessing basic user profile but I want the user data to display in JSON format .

    please can you tell me the way to achieve it

    Regards
    Anil Kumar

    • Avatar Vinu says:

      Did You got any solution for this… Am also looking as you asked.

    • Avatar Nishanth Kabra says:

      Hi Anil, since you got it working working can you help me do the same. am facing an issue with authorization and kind a stuck there. can you please read and reply to my recent same question? Any pointers will be hellpful.

  • Avatar Xavi says:

    Hi Nic,

    I have two question. When I create my Facebook App, should be www or a specific operating system?

    and the second question, this work fine on Ionic view?

    Regards

    • Avatar Łukasz Gosławski says:

      I have struggled to test facebook under ionic view on ios, but it works for me in emulator (after compiling) so I assume it will be fine. as for android, it works fine in ionic view and emulator.

  • Avatar Muhammad Waseem says:

    Cominform is your partner for efficient, custom-tailored business software-solutions. The Cominform team develops on innovative platforms and in line with cutting-edge standards. Here are options for Web Desktop,Web-Desktop, SAML Cordova Plugin , SQL Cordova Plugin , SAML Phonegap Plugin and SQL Phonegap Plugin.

  • Avatar airnold says:

    Hi~

    how can i get instagram profile ??

    i’ve got access token successfully! but i dont know how can i get user data..

    • Avatar angelxmoreno says:

      That is not related to this article. you will have to look at the Instagram API and the Angular $http service.

  • Avatar Sariyu Datla says:

    It is not using the facebook account credentials in mobile app. asking separately. How can we make to use already logged in facebook app credentials ?

  • Avatar Elham Sarikhani says:

    Can cordovaOauth be used for another provider which is not listed in the documentation?

  • Avatar William Chantry says:

    Anyone notice any security concerns with using this method?

  • Avatar andylockran says:

    I’m struggling with being able to access $cordovaOauth with ngCordova installed. I’ve successfully got the barcodeScanner plugin working, but whenever I refernece $cordovaOauth in a controller I get an unknown Provider error..

  • Avatar tombrokeoff says:

    Hoping somebody can chime in with some advice. So far I have an Ionic app that uses oauth to allow a user to sign into Facebook. I am successfully getting the short lived token back. I am then passing that on to my server, which in turn, sends it back to Facebook in exchange for the long lived token. All of this is working fine, but what I need to know, once I get that back, should I store it in a database and allow the user/app to get it from there via the server, or should I return it to the user immediately and store it on the device? Appreciate any guidance. Thanks.

  • Avatar Павел Хребто says:

    Hi everybody. Currently on latest build everyone will have “Unknown provider” error, as ngCordov lib was changed.

    Now you should use $cordovaFacebook.login or $cordovaGooglePlust.login methods instead.

  • Avatar Nishanth Kabra says:

    Hi author, am trying to include google sign in in my ionic app however am facing authorization issues. Heres what i am seeing
    1. I see the google login screen
    2. I enter username and password
    3. I see my google app consent screen(I say allow)
    4. The network call says the invalid acess token to user profile google api.

    Following is code snippet.

    function loginGoogle() {

    var defer = $q.defer();

    $cordovaOauth.google(“xxxxxxxxxxxxxxxxx”, [“https://www.googleapis.com/auth/userinfo.email”, “https://www.googleapis.com/auth/userinfo.profile”])

    .then(function (result) {

    var token = result.access_token;

    var getUserInfo = $http({

    url: ‘https://www.googleapis.com/oauth2/v3/userinfo’,

    method: ‘GET’,

    headers: { “Authorization”: “Bearer” },

    params: { access_token: token }

    });

    getUserInfo.then(function (res) {

    defer.resolve(res);

    }, function (err) {

    alert(“There was a problem getting your profile. Check the logs for details.”);

    defer.reject(err);

    });

    }, function (error) {

    console.log(error);

    defer.reject(error);

    });

    return defer.promise;

    }

  • Avatar Umit Sadeguzel says:

    Hi, when i try to login to Google via “https://accoutns.google.com/o/oauth2/auth?client_id=xxxx.apps.googleusercontent.com&redirecituri=http://localhost/callback&scope=https://wwww.googleapis.com/auth/urlshortoner%20https://www.googleapis.com/auth/userinfo.email&approval_prompt=force&response_type=token ” page can not be loaded. This was working well in january, is there any update in Google side or in library

  • Avatar rejinthala manoj says:

    how can we get the client id

  • Avatar Dery Feb says:

    Hi nic, I’m using this plugin and it works like a charm when i build in android platform but when i build in bb10 platform and try the Oauth, after granted the app and redirecting to callback url the screen dispaly “network unavailable” and i check the inspector web page/console it output “Failed to load resource: Couldn’t connect to server http://localhost/callback?oauth_token=0VhWiQAAAAAAjuptAAABUtO9uDU&oauth_verifier=x6VgMU8dBI06YacTX90rOqn4“, is this plugin doesn’t support bb10 platform? or what am i missed something? thanks in advance.

  • Avatar hva.narola says:

    Hello
    I am getting this error after trying to access data with token i got
    {“errorCode”:0,”message”:”Mutiple authentication schemes detected”,”requestId”:”XB39L6MCP4″,”status”:401,”timestamp”:1456385309906}
    can you lease help me with the problem.
    here is the function am calling in success of token

    function Getdata(){

    $http.defaults.headers.common.Authorization = “Bearer ” + window.localStorage.getItem(“access_token”);

    $http.get(“https://api.linkedin.com/v1/people/~:(id,first-name,last-name,email-address,public-profile-url)?oauth2_access_token=”+window.localStorage.getItem(“access_token”)+”&format=json”).success(function(data) {

    console.log(JSON.stringify(data.droplets));

    }).error(function(error) {

    console.log(error);

    });

    }

  • Avatar simi says:

    Hi, when I tried to log in via linkedin. I got the following error. any ideas ?

    code:

    $cordovaOauth. linkedin(“MY_CLIENT_ID_XXXX”,”MY_SECRECT_XXXX”, [“email”]).then(function(result) {

    console.log(“Response Object -> ” + JSON.stringify(result));

    }, function(error) {

    console.log(“Error -> ” + error);

    });

    ********************LOG*******************
    TypeError: appScope.join is not a function

    at Object.oauthGoogle [as google] (file:///android_asset/www/lib/ng-cordova-oauth.js:692:182)

    at Scope.$scope.loginLinkedin (file:///android_asset/www/js/login/login.controller.js:18:18)

    at fn (eval at (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:26457:15), :4:230)

    at file:///android_asset/www/lib/ionic/js/ionic.bundle.js:62386:9

    at Scope.$eval (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:29158:28)

    at Scope.$apply (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:29257:23)

    at HTMLButtonElement. (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:62385:13)

    at HTMLButtonElement.eventHandler (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:16583:21)

    at triggerMouseEvent (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:2948:7)

    at tapClick (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:2937:3)(anonymous function) @ ionic.bundle.js:25642(anonymous function) @ ionic.bundle.js:22421Scope.$apply @ ionic.bundle.js:29259(anonymous function) @ ionic.bundle.js:62385eventHandler @ ionic.bundle.js:16583triggerMouseEvent @ ionic.bundle.js:2948tapClick @ ionic.bundle.js:2937tapTouchEnd @ ionic.bundle.js:3064

    2016-02-26 14:23:26.316 whitelist.js:26 No Content-Security-Policy meta tag found. Please add one when using the cordova-plugin-whitelist plugin.

  • Avatar shash says:

    how to set callback URIs to point http://localhost/callback; otherwise…
    Thanks in Advance…

    • Avatar ARCreative says:

      It looks like it does this for you for most of the plugins. The callback_url isn’t exposed since allowing you to change it would likely break the implementation.

  • Avatar Aveg says:

    How to get the linkedin state which is the 4th parameter for linked in oAuth?

  • Avatar simon le says:

    Hi Nic, I’m having to auth ionic app with magento but in magento rest api only support oauth 1.0, your library use oauth 2.0 with magento, can you help me problem yet ? Thanks you

  • Avatar a_user says:

    Nic Raboy this plugin has helped my alot, thanks.
    when i use $cordovaOauth.twitter(), i get oauth_token, oauth_token_secret, user_id, screen_name, x_auth_expires. how would i use these to get the user’s details like name and user id?

  • Avatar Francisco Re says:

    Why it doesn’t work on the browser?

  • Avatar malaise says:

    I think “https://www.googleapis.com/auth/userinfo.email” is depreciated now by Google. It’s better to use “https://www.googleapis.com/auth/plus.profile.emails.read” ( https://developers.google.com/+/web/api/rest/oauth#authorization-scopes )

  • Avatar Satyam says:

    For Google+
    I am getting JSON file.
    So, I need to use client id as :

    “oauth_client”: [

    {

    “client_id”: “637010922851-t0rqmlloemurdpbv0as5m9bvnu5ke57t.apps.googleusercontent.com”,

    “client_type”: 1,

    “android_info”: {

    “package_name”: “com.ionicframework.loginauth268425”,

    “certificate_hash”: “B4D0AE12434AB3B175E593B98A0D6F955B5D0BA0”

    }

    },

    Auth client id or “client_id”: “637010922851-0rh553i409gpku6785131kmf4gd09598.apps.googleusercontent.com”,

    As I am facing issue . I didn’t getting evn auth screen.

  • Avatar andylockran says:

    I’m working on Mondo OAuth integration; just setting it up as a new provider: https://github.com/andylockran/ng2-cordova-oauth/tree/feature/MondoAuthentication/

    They’re using a magic link that hits your email inbox, and then redirects to the callback URL from a link in the email. http://localhost/callback obviously fails in this instance, as you’re then not in the inAppBrowser, but your standard web client.

    Is it right to switch to using an app URL Scheme, and how compatiable would that be across android/ios ?

  • Avatar tanveer says:

    i can only login with my own fb account i want to release the app what to do in facebook console to release the app.

  • Avatar Nagarjun bn says:

    Completed google and facebook authentication in 1hr. Thanks @nic

  • Avatar Sumit S Jaju says:

    Hey Nick, what strategy would be best for email signUp (application’s own signUp process). I have used passport js for web browser but not sure what will be the best for ionic app. Please suggest.

  • Avatar vishal says:

    Getting following error :-

    ionic.bundle.js:23484 Error: [$injector:unpr] Unknown provider: $cordovaOauthProvider <- $cordovaOauth

    There is no such provider exist $cordovaOauth. where is it.

  • Avatar rejinthala manoj says:

    what is redirect URI while giving the app details in developers.google.com

  • Avatar rejinthala manoj says:

    what is redirect URI while giving the app details in developers.google.com

  • Avatar rejinthala manoj says:

    how can i integrate twitter login to ionic app

  • Avatar Ionic Facebook says:

    any one used for ionic v2 llogin with linked for code

  • Avatar HR PATEL says:

    any one used for ionic v2 login with linked for code

  • Avatar HR PATEL says:

    how can i integrate linkedin login to ionic 2
    app

  • Avatar Marcos Arata says:

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

  • Avatar Harshad Dusane says:

    New to ionic ,can you help me to integrate linked in with ionic?

  • Avatar Simerjit says:

    I am unable to get email while logging in through twitter. I have changed permissions over twitter to get email address. Still not able to get email… Any solution??

  • Avatar Ifeora Okechukwu says:

    Nice Tuts!!

  • Avatar pfooti says:

    Under what circumstances is it advisable to put your client id and secret in code that is distributed to users?

  • Avatar Rangholiya Nikunj says:

    getting following error :

    Error: [$injector:unpr] Unknown provider: $ionicGoogleAuthProvider <- $ionicGoogleAuth <- homeCtrl

3 Trackbacks