Add Google+ Login to your Ionic App

by - April 02, 2017



Authentication options

Authentication is a key component for your app, and there are some different approaches that you can take.

The handcrafted way (using your own API/Backend)

If you already have an API or backend that handles user authentication, or if you are one of those who like to have strict control over the backend implementation, then this may be your option.
Mobile apps require a different authentication strategy than web apps or websites. You don’t have sessions so you have to go with the token based authentication. For my clients production apps I use Strongloop. Basically is a platform that enables you to easily build custom API’s for your backend needs. It comes with token based authentication and an AngularJS SDK that works smoothly in your Ionic app. (You can read more about how easy is to manage users in this post “Managing users with StrongLoop”)

The BaaS way

If you don’t want to take care of your own infrastructure and backend implementation, then there are a few BaaS (Backend aa Service) options.
Firebase is a great service that will help you build your app’s backend with ease. (owned by Google). You can read more about this on this post “Logging Users In with Firebase”.
The guys from Ionic recently launched the Ionic Platform which is a BaaS solution with very useful services to build mobile apps. This platform offers cool features among push notifications and user authentication. We have made a tutorial to show you how to add Ionic Platform authentication into your Ionic app.

The Social way

You can choose to provide authentication using well known social networks such as Facebook, Instagram, TwitterGoogle, etc. In this post we will explore how to add Google+ native authentication to your Ionic app.
Each option has it’s benefits, and of course you can mix them together and have an even more complete solution and experience for your users. It’s very common to see different ways of authenticating users within an app.

Google+ Authentication

There are different ways to integrate Google+ authentication into your Ionic app. However, not all of them use the native approach which uses Google+ app to perform the login instead of opening a popup requesting users to enter their credentials to login to Google+ before granting access to your app.
The way it works for hybrid apps to use native api’s and sdk’s is simple, you need a piece (typically a PhoneGap/Cordova plugin) that connects native api’s and sdk’s with the javascript environment where the hybrid apps run. In this case we are going to use a great cordova plugin to interact with the native google sdk.
We will use Google+ Cordova/PhoneGap Plugin to login with Google+ on iOS and Android. This plugin was developed by Eddy Verbruggen and it allows you to log in with your Google account on iOS and Android. You will not only get the email address of the user, but also stuff like their full name and gender.

Hands on!

Remember ... you will need:

  • An Ionic app where you will integrate this login. You can either use a blank app, or an existing one.
  • To follow the setup steps for android (to enable google+ login on android)
  • To follow the setup steps for iOS (to enable google+ login on iOS)
  • The Google+ Cordova/PhoneGap Plugin to interact with the device native API's
Ad time!: If you are looking for a beautiful starter app with login UI/UX you must have a look at our beautiful mobile themes, templates & components. Specially our Logins Category.

This is how it will look like

iOS

Android

Step 1: Setup to communicate with Google+

There are some configurations you need to set in order to communicate your app with Google+

For iOS

For Android

Step 2: Install required cordova plugin to interact with Google+ native SDK

After you have done all the above configurations, it’s time to install the plugin into your app. Follow these steps to get this DONE:
  • Using your terminal window, go to your Ionic app folder
  • Run the following command to install the plugin changing the variable with your own value:
    $ cordova plugin add cordova-plugin-googleplus --variable REVERSED_CLIENT_ID=myreversedclientid
GooglePlus.js is brought in automatically. There is no need to change or add anything in your html.
To see other ways to install the plugin or if you are using Phonegap Build, go to the plugin documentation.

What we have done so far:

  • An Ionic app (existing or new one)
  • A Google app with the proper configurations
  • GooglePlus Plugin installed into your Ionic app








Step 3: Adding Login/Logout functionality

Now we will go straight to the code so open your Ionic app with your preferred code editor. Personally I use and recommend atom.

Login

The best way to show you how to add Login functionality is with a real example of the code, here you can see an AngularJS controller that handles the Google+ login for your app.
.controller('WelcomeCtrl', function($scope, $state, UserService, $ionicLoading) {
  // This method is executed when the user press the "Sign in with Google" button
  $scope.googleSignIn = function() {
    $ionicLoading.show({
      template: 'Logging in...'
    });

    window.plugins.googleplus.login(
      {},
      function (user_data) {
        // For the purpose of this example I will store user data on local storage
        UserService.setUser({
          userID: user_data.userId,
          name: user_data.displayName,
          email: user_data.email,
          picture: user_data.imageUrl,
          accessToken: user_data.accessToken,
          idToken: user_data.idToken
        });

        $ionicLoading.hide();
        $state.go('app.home');
      },
      function (msg) {
        $ionicLoading.hide();
      }
    );
  };
})
Then in your html you should add a “Sign in with Google” button
<a class="google-sign-in button button-block" ng-click="googleSignIn()">Sign in with Google</a>

Logout

The following controller contains all the necessary code for the Google sign out:
.controller('HomeCtrl', function($scope, UserService, $ionicActionSheet, $state, $ionicLoading){
 $scope.user = UserService.getUser();

 $scope.showLogOutMenu = function() {
  var hideSheet = $ionicActionSheet.show({
   destructiveText: 'Logout',
   titleText: 'Are you sure you want to logout? This app is awsome so I recommend you to stay.',
   cancelText: 'Cancel',
   cancel: function() {},
   buttonClicked: function(index) {
    return true;
   },
   destructiveButtonClicked: function(){
    $ionicLoading.show({
     template: 'Logging out...'
    });
    // Google logout
    window.plugins.googleplus.logout(
     function (msg) {
      console.log(msg);
      $ionicLoading.hide();
      $state.go('welcome');
     },
     function(fail){
      console.log(fail);
     }
    );
   }
  });
 };
})
Then in your html you should add a “Log out” button
<a class="button button-assertive button-block button-outline" ng-click="showLogOutMenu()">Log Out</a>

Services

You also will need some services to store and get your user’s data. For the purpose of this example I will store user data on the device local storage but you should save it on a database.
angular.module('services', [])
.service('UserService', function() {
 // For the purpose of this example I will store user data on ionic local storage but you should save it on a database

  var setUser = function(user_data) {
    window.localStorage.starter_google_user = JSON.stringify(user_data);
  };

  var getUser = function(){
    return JSON.parse(window.localStorage.starter_google_user || '{}');
  };

  return {
    getUser: getUser,
    setUser: setUser
  };
});

What we have done so far:

  • At this point you should have an Ionic app with Google login and logout functionalities working.

You May Also Like

0 comments