Logo
  • TEMPLATES
  • TUTORIALS
  • ANGULAR TEMPLATES
  • REGISTER
  • LOGIN

Learn Ionic Framework with free step by step ionic tutorials

All you have to know about Ionic Framework, the best tips and free code examples so you can get the most out of Ionic Framework.

Add Google+ Login to your Ionic App

By Dayana Jabif / posted on October 2, 2015
GET THE CODE

Register

Ionic 1AuthenticationGoogle LoginLogin
  • Post Summary
  • Requirements

In this post you will learn how to add Google+ Login to your Ionic app.

As an example we are going to build a simple app that allows users to login to your app using their Google+ account. Once they log in, they will see a home page with their basic profile info.

Requirements

  • You need an Ionic app where you will integrate this login. You can either use a blank app, or an existing one.
  • You need to follow the setup steps for android (to enable google+ login on android)
  • You need 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

References

  1. Google+ Cordova/PhoneGap Plugin


Note: This post is for Ionic 1. If you are working with Ionic 3, 4 or 5 go to Add Google Login to your Ionic App.

Introduction

Congratulations, you have made a great decision by choosing Ionic to build your app. (You can read more why I believe this in this post “Ionic FTW”).

In this blog you will find lots of content that will guide you on building and shaping beautiful mobile apps.

In particular, this post will be about adding Google NATIVE authentication to your Ionic app. This will enable an easy and elegant way for your users to login to your app.

Why adding Google+ Authentication into your app will benefit you and your users?

  • Improve conversions: Help people log into your app quickly without having to remember another username and password.
  • One login across every device: Make it easy for people to log in and access their info across multiple platforms and devices.
  • Build a trusted relationship: Give people control over the info they share with your app.
  • Access profile info: like picture, gender, age, name, without having to ask for it.

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 as a 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, Twitter, Google, 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

  • To get your iOS API key, follow Step 1: Creating the Google Developers Console project of the guide to Start integrating Google+ into your iOS app.
  • Enable Google services for your app to get a configuration file GoogleService-Info.plist which contains the REVERSED_CLIENT_ID that you will need during the plugin’s installation.

For Android

  • Follow Step 1: Enable the Google+ API of the guide: Quick-start sample app for Android.
  • Make sure you execute the keytool steps or authentication will fail.

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.

Next Steps

After having the authentication working you can focus on:

  • Learn how to build a complete Ionic app step by step
  • The routing and adding access control to certain pages within your app
  • Store users and tokens in your own database
  • Using analytics tools to track users and what they do in your app
  • Integrate other authentication methods so your users have more options to choose from.
  • Prettifying your app using a theme or your design skills, taking advantage of the many possibilities that Ionic and Sass provide
  • Integrate and make use of other Google+ API endpoints to give more powers to your app.

As you know we also sell beautiful mobile themes, templates and components that you may find super useful as they save you hours of development, time and effort, while giving your projects a great design from scratch. Having said that we have a line of Login / Authentication components that would be the perfect match for your Google+ integration.

The authentication step is the first screen of your app that your users will see, so it’s very important that you pay attention to its appearance.

Here you can experience some of the components we have to offer you:

Enjoyed reading this Ionic Tutorial?

Subscribe to keep learning Ionic Framework! You will receive offers, new ionic tutorials and free code examples from IonicThemes.

Watch these videos and start building your Ionic apps now!

Prefer videos?
Check our
YouTube Channel
Author

By Dayana Jabif

Full stack developer and JS lover. Motivated by living a free & happy life.
Follow me on

IONIC TUTORIALS

AdMobApp ShellAuthenticationBeginnersCamera AccessCapacitorDatabaseDesign TipsFacebook LoginFirebase IntegrationForm ValidationsFormsGeolocationGoogle LoginGoogle MapsGoogle PlacesInternationalizationIonic 1Ionic 2Ionic 3Ionic 4Ionic 5LocalizationLoginNavigationProgressive Web AppsPush NotificationsSocial SharingStencilTwitter LoginUIUXWeb ComponentsWordpress Integration

ionic templates

TABLE OF CONTENT

  • Introduction
  • Authentication Options
  • Google+ Authentication
  • Hands On!
  • Step 1: Setup to communicate with Google+
  • Step 2: Install required cordova plugin to interact with Google+ native SDK
  • Step 3: Adding Login/Logout functionality
  • Next Steps

angular templates
There are no products matching the selected filters

Liked this Ionic Tutorial? Leave your comments below.


Sign up to receive offers and ionic free code examples!
FOLLOW US

Our aim is to help people of different skill levels - designers or developers - get the most out of Ionic Framework by saving your expensive time and providing great resources for you to learn ionic framework faster and better. In IonicThemes you will find premium Ionic Starters and Ionic Framework tutorials, tips and tricks.

RESOURCES
  • IONIC STARTERS
  • IONIC TUTORIALS
  • ANGULAR TEMPLATES
  • DESIGN INSPIRATION
SUPPORT
  • FAQS
  • CONTACT US
OTHERS
  • AFFILIATES
  • ABOUT US
  • TERMS & CONDITIONS
  • PRIVACY POLICY
2020 StartApp Labs
Mobile Analytics