Mobile
Article

Authenticating Users via OAuth with Cordova and Ionic

By Jay Raj

This article was peer reviewed by Wern Ancheta. Thanks to all of SitePoint’s peer reviewers for making SitePoint content the best it can be!

Authenticating users to a service is an essential part of mobile apps. It allows you to ensure the correct users are accessing your service and enables you to personalize what you offer them. There are many authentication methods available, but authenticating users via OAuth is a long time favorite for developers. It’s an open standard for authorization which allows users to sign in to applications using their accounts on other services (such as Facebook, Google etc) without giving the application access to any credentials. In this tutorial, I’ll look at cordovaOAuth is an AngularJS extension which allows mobile developers to add Oauth authorization to their Cordova based apps as simple as possible.

The Project

There are a lot of third party websites which provide OAuth authorization, the most popular being Google, Facebook, GitHub, and LinkedIn. In this tutorial, I’ll show you how to implement OAuth authorization using a Google account with the help of $cordovaOauth. I’ll use the Ionic framework for creating the mobile app. If you’ve never used Ionic before, I recommend you read my tutorial, “Creating a Bucket List with the Ionic Framework and Firebase

The source code from this tutorial is available on GitHub.

Getting Started

You will need to install Cordova (I recommend SitePoint’s QuickTip) and the Ionic framework (again, I recommend SitePoint’s QuickTip)

Note: This example will use the Android platform.

Create an Ionic app using the tabs template.

ionic start myGoogleIonicApp tabs

Navigate to the project directory myGoogleIonicApp and run the server.

ionic serve

You should now have the app running at http://localhost:8100.

Default App Screen

Installing ngCordova and $cordovaOauth

Navigate to the myGoogleIonicApp directory and install ngCordova using bower (Yes, of course SitePoint has a QuickTip!).

bower install ngCordova

Include the ngCordova script before the cordova script in the index.html page.

<script src="lib/ngCordova/dist/ng-cordova.js"></script>
<script src="cordova.js"></script>

Add the $cordovaOauth plugin to the project.

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

Install ng-cordova-oauth in the project.

bower install ng-cordova-oauth

Include the $cordovaOauth script after the ngCordova script in the index.html page.

<script src="lib/ng-cordova-oauth/dist/ng-cordova-oauth.js"></script>

Creating the User Interface

Navigate to www/templates/tab-dash.html and replace the existing code with this code:

<ion-view view-title="Dashboard">
  <ion-content class="padding">
    <h2>Welcome to Ionic</h2>
    <div>
      <a href="" ng-click="googleLogin()"><button>Login With Google</button></a>
    </div>
  </ion-content>
</ion-view>

Add the Android platform to the mobile app and build the code:

ionic platform add android
ionic build android

Run the application with:

ionic run android

And you should see the below:

Google Login App

Implementing OAuth Using Google Login

Navigate to www/js/app.js and inject the ngCordova and ngCordovaOauth module.

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

Inside www/js/controllers.js add the googleLogin function inside DashCtrl as shown :

.controller('DashCtrl', function($scope, $cordovaOauth, $http) {

    $scope.googleLogin = function() {
        $cordovaOauth.google("app-id", ["email", "profile"]).then(function(result) {

        }, function(error) {

        });
    }
})

Breaking down the above code, you injected the cordovaOauth module into the DashCtrl controller, and using the cordovaOauth module you called the Google API. You will need an application key to enable Google OAuth Login which you can get from the Google developer console. Once logged in, click on the right side corner drop down to create a new project.

Create new project Google Developer Console

Click on the credentials tab on the left side menu and click the Create credentials button.

Create credentials

Select OAuth Client ID from the menu and click Create credentials.

enter image description here

Select the Application type as Web Application, set the callback URL and click Create as shown :

Set Application Type

Once you have created the client it should show the client ID, copy the value and add it to the googleLogin method in DashCtrl.

$scope.googleLogin = function() {
        $cordovaOauth.google("YOUR GOOGLE CLIENT ID", ["email", "profile"]).then(function(result) {
            $scope.details = result.access_token;
        }, function(error) {
          // Error code here
        });
    }

Next you need to bind the scope.details to the user interface to see if it works. Change www/templates/tab-dash.html as shown :

<ion-view view-title="Dashboard">
  <ion-content class="padding">
    <h2>Welcome to Ionic</h2>
    <div>
      <a href="" ng-click="googleLogin()"><button>Login With Google</button></a>
      <span>{{details}}</span>
    </div>
  </ion-content>
</ion-view>

Save the changes, build the ionic app and deploy the .apk file to the device. Run the app and click to login using Google account. On a successful login you should be able to see the access token displayed on the app screen.

Pulling User Info With Access Token

Using the access token, extract the user info and display it in the app. Inside the googleLogin function, make an http call to the Google APIs to get the user information.

$http.get("https://www.googleapis.com/plus/v1/people/me", {
        params: {
            access_token: result.access_token
        }
    })
.then(function(res) {
    // success callback
}, function(error) {
    alert("Error: " + error);
});

In the success callback function, bind the user info to a scope variable and display it in the app.

$scope.details = res.data;

Now change the user interface by adding a class to the existing button.

<div>
  <a href="" ng-click="googleLogin()"><button class="button button-block button-positive">Login With Google</button></a>
</div>

To display the user information, add a list as shown below:

<div ng-show="showProfile" class="list">
  <a class="item item-avatar" href="#">
    <img ng-src="{{details.image.url}}">
    <h2>{{details.displayName}}</h2>
    <p>Back off, man. I'm a scientist.</p>
  </a>
</div>

You added the showProfile scope variable to hide the list when the app loads, set the showProfile variable to true when the googleLogin method fetches the user info.

$scope.showProfile = true;

Here is the complete googleLogin method:

$scope.googleLogin = function(){

  $cordovaOauth.google("YOUR GOOGLE CLIENT ID", ["email","profile"]).then(function(result) {

      $scope.showProfile = false;
      $http.get("https://www.googleapis.com/plus/v1/people/me", {params: {access_token: result.access_token }})
      .then(function(res) {

       $scope.showProfile = true;
       $scope.details = res.data;

      }, function(error) {
          alert("Error: " + error);
      });

  },function(error) {
        // error
        $scope.details = 'got error';
    });
}

Save the changes, build the ionic app and run it. Try to login by clicking on the Login With Google button and on successful authentication user info should display in the app.

OAuth App Using ngCordova Plugin

Do more with ngCordova plugins

In this tutorial you learnt how to add OAuth authentication to a Cordova and Ionic based app using the ngCordova plugin, cordovaOauth. If you’re interested in learning more about other plugins that may help your development, I recommend reading the ngCordova official documentation.

Please let me know your comments and questions below.

  • http://www.brainmobi.com Shrestha Tripathi

    What an article with point to point explanation.Thanks for sharing.

  • Shamroz Warraich

    can u help me in ionic 2 for making this app…?

  • http://nicholls.azurewebsites.net/ Juan David Nicholls

    Check my Angular Service! :D You can use the new firebase to support browser platform too yay! https://gist.github.com/jdnichollsc/17bae6581d405321937fe433410172c9

Recommended

Learn Coding Online
Learn Web Development

Start learning web development and design for free with SitePoint Premium!

Get the latest in Mobile, once a week, for free.