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.

Google Login for Ionic 4

By Dayana Jabif / updated on February 25, 2019
GET THE CODE

Register

LoginGoogle LoginAuthenticationIonic 4
  • Post Summary
  • Requirements

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

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

Requirements

  • You need an Ionic 3 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 Sign-In Cordova/PhoneGap Plugin to interact with the device native API's

References

  1. Google Sign-In Cordova/PhoneGap Plugin

Google Authentication in Ionic Apps

In this ionic framework tutorial we are going to show you - step by step - how to integrate Google Plus Authentication to your Ionic applications. This will enable an easy and elegant way for your users to log in to your mobile and web apps.

Why adding Google+ Authentication into your ionic 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 some production apps we use Loopback. 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 Angular SDK that works smoothly in your Ionic apps. You can learn more about how to integrate Loopback to your Ionic App in: Building a complete mobile app with Ionic Framework.

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 very popular service that will help you building the backend for your ionic framework application. Firebase is a popular tool that helps you build apps fast, without managing infrastructure. It’s also a powerful Database as a Service (DBaaS) solution which provides a scalable NoSQL cloud database to store and sync data for client and server side development. Firebase is built on top of Google infrastructure and allows you to scale automatically, so you don’t need to worry about scaling your own servers. You can read the following tutorial to learn how to handle Firebase authentication in Ionic 5 Apps.

The Social way

You can choose to provide authentication using well known social networks such as Facebook, Instagram, Twitter, Google, etc. We think that in these days, this is the best way to authenticate your users because it's easier for them, so we have created a set of detailed tutorials to help you implementing this in your apps.

  • Add Facebook Authentication to your Ionic 4 App.
  • Add Twitter Authentication to your Ionic App.

In this ionic 4 tutorial we will explore how to add Google+ native authentication to your Ionic 4 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.

If you need help starting with your Ionic App, I suggest you to take a look at Ionic Starter Template - The most complete Ionic Starter App. It will save you lots of development and design hours and it alreay has lots of useful features that you will love! Check some of the authentication screens available in the template.

Ionic 4 authentication
Ionic 4 log in
Auth in Ionic 4
Check Ionic Starter 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 very simple. We need a piece (typically a Cordova plugin) that connects native API’s and SDK’s with the javascript environment where the ionic app runs. For this example ionic app we are going to use a cordova plugin to interact with the native Google SDK.

We will use Google Sign-In 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. Using this plugin you will get email, display name, given name, family name, profile picture url, and user id.

Ionic Google Authentication

For this Ionic example app you will need:

  • An Ionic app where you will integrate this login. You can either use a blank app, or an existing one.
  • Follow the setup steps for Android (to enable Google login on Android).
  • Follow the setup steps for iOS (to enable Google login on iOS).
  • The Google Sign-In Cordova/PhoneGap Plugin to interact with the device native API's.

Our Ionic demo app will look like this:

Google API setup

There are some configurations you need to set in order to communicate your app with Google Plus. Please read each step carefully.

Important note!

Open your config.xml and make sure that your package name is what you want it to be (i.e. io.ionic.ionic4GoogleLogin). Use this name when setting up Android and iOS in the following steps. If you don't, you will probably get a 12501, 'user cancelled' error. For example this is the name of this ionic demo app:

<widget id="io.ionic.ionic4GoogleLogin" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">

Configuring iOS

You will need to generate a configuration file (GoogleService-Info.plist) in order to get a REVERSED_CLIENT_ID which you will need during the plugin installation process. Let's see how to do it!

The first step is to Create a New Project in the Firebase Console. Wait, why do we need to create a Firebase project if we are on a Google Sign In tutorial with Ionic Framework?. You need to create a Firebase project in order to use Google Cloud features on your mobile app such as google sign in, google maps, google places, and so on.

Add Firebase Project

Now go to the "Project Settings" section of your new Firebase project, scroll down to "Your Apps" and click on "Add App". A modal will open and you need to click on "Add Firebase to your iOS App".

Add iOS App

The final step is to register the iOS App using the package name of your Ionic App as the iOS bundle ID. The other fields are optional. Then click "Register App" and now you will be able to download the configuration file: GoogleService-Info.plist. Open this file and you will be able to see the REVERSED_CLIENT_ID.

firebase iOS App
Some notes about iOS:
  • The REVERSED_CLIENT_ID value is only needed for iOS.
  • Please note that the REVERSED_CLIENT_ID value is also known as the "iOS URL Scheme" on the Developer's Console.
  • Authentication on iOS takes the user to a SafariViewController through the Google SDK.

Configuring Android

For Android, you will also need to generate a configuration file. This file is named google-services.json. Let's see what we need to do.

If you already created a new project on the Firebase Console for iOS, use it, otherwise create a new one.

Now go to the "Project Settings" section of your new Firebase project, scroll down to "Your Apps" and click on "Add App". A modal will open and you need to click on "Add Firebase to your Android App".

Add Android App

The final step is to register the Android App using the package name of your Ionic App as the Android Package Name. The other fields are optional. Then click "Register App" and now you will be able to download the configuration file: google-services.json.

firebase Android App
Some notes about Android:
  • Once Google Sign-In is enabled, Google will automatically create the necessary credentials in the Developer Console. Please note that there is no need to add the generated google-services.json file into your Ionic project.
  • Important! Make sure you execute the keytool steps as explained in Google's documentation to get the Debug signing certificate SHA-1 or the authentication will fail.
  • Authentication on Android will use the accounts signed in on the user's device.

Install cordova plugin to interact with Google Plus SDK

Before we start, I want to remember you that you can download for free the code of this ionic project by clicking the GET THE CODE button from the beginning of the page.

After you have done all the above configurations, it’s time to install the plugin into your ionic framework 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:

    $ ionic cordova plugin add cordova-plugin-googleplus --save --variable REVERSED_CLIENT_ID=YOUR_REVERSE_CLIENT_ID

    $ npm install --save @ionic-native/google-plus@beta

Notes:

  • YOUR_REVERSE_CLIENT_ID is your value of REVERSED_CLIENT_ID and should look like this: com.googleusercontent.apps.uniqueId
  • GooglePlus.js library is brought in automatically. There is no need to change or add anything in your Ionic app's html.

To see other ways to install the plugin or if you are using Phonegap Build, please refer to the plugin documentation.

What we have done so far:

  • Create an Ionic app (existing or new one).
  • Create a Google app with the proper configurations.
  • Install GooglePlus Plugin in your Ionic Framework app.

Add Google Auth to your Ionic App

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

Ionic Google Login

The best way to show you how to add Login functionality is with a real example of the code, here you can see some Typescript code that handles the google authentication for your app.

The login function walks the user through the Google Auth process. All parameters are optional, however there are a few gotchas.

  • To get an idToken on Android, you must pass in your webClientId (a frequent mistake is to supply Android Client ID). On iOS, the idToken is included in the sign in result by default.
  • To get a serverAuthCode, you must pass in your webClientId and set offline: true. If offline is true, but no webClientId is provided, the serverAuthCode will NOT be requested.
  • Permissions: The default scopes requested are profile and email. To request other scopes, add them as a space-separated list to the scopes parameter.
async doGoogleLogin(){
	const loading = await this.loadingController.create({
		message: 'Please wait...'
	});
	this.presentLoading(loading);

	this.googlePlus.login({
		'scopes': '', // optional, space-separated list of scopes, If not included or empty, defaults to `profile` and `email`.
		'webClientId': 'webClientId.apps.googleusercontent.com', // optional clientId of your Web application from Credentials settings of your project - On Android, this MUST be included to get an idToken. On iOS, it is not required.
		'offline': true // Optional, but requires the webClientId - if set to true the plugin will also return a serverAuthCode, which can be used to grant offline access to a non-Google server
	})
	.then(user =>{
		loading.dismiss();

		this.nativeStorage.setItem('google_user', {
			name: user.displayName,
			email: user.email,
			picture: user.imageUrl
		})
		.then(() =>{
			this.router.navigate(["/user"]);
		}, error =>{
			console.log(error);
		})
		loading.dismiss();
	}, err =>{
		console.log(err)
		loading.dismiss();
	});

	async presentLoading(loading) {
		return await loading.present();
	}
}

You can get your webClientId in https://console.developers.google.com/apis/credentials.


Then in your html you should add a “Sign in with Google” button

<ion-button expand="block" color="danger" (click)="doGoogleLogin()">Google Login<ion-button>

Ionic Google Logout

To perform Google log out we will call the googlePlus.logout() method that will invalidate the token generated at log in. Also, we will remove from the native storage the data from the logged user.

We will use the following code to perform the Google sign out functionality:

doGoogleLogout(){
	this.googlePlus.logout()
	.then(res =>{
		//user logged out so we will remove him from the NativeStorage
		this.nativeStorage.remove('google_user');
		this.router.navigate(["/login"]);
	}, err =>{
		console.log(err);
	})
}

NativeStorage

NativeStorage is a Cordova plugin which provides persistent storage of primitives native in Android, iOS and Windows. It's created because of the non-persistent property of LocalStorage in the WebView of Android and iOS. In iOS stored data from LocalStorage can be removed by the OS, when running out of memory.

To install this plugin just run the following command in your ionic project:
$ ionic cordova plugin add cordova-plugin-nativestorage --save
$ npm install --save @ionic-native/native-storage@beta

We added a check inside the platform.ready() in app.component.ts to check if the user is already logged in. In case the user is logged in we navigate to the User page, if not, we navigate to the Log In page.

platform.ready().then(() => {
	//Here we will check if the user is already logged in
	//because we don't want to ask users to log in each time they open the app
	this.nativeStorage.getItem('google_user')
	.then( data =>{
		// user is previously logged and we have his data
		// we will let him access the app
		this.router.navigate(["/user"]);
		this.splashScreen.hide();
	}, error =>{
		this.router.navigate(["/login"]);
		this.splashScreen.hide();
	});
	this.statusBar.styleDefault();
});

Testing the functionalities

At this point you should have an Ionic application with Google log in and log out functionalities working. To test the native implementation you need to test the app on a real device or in an emulator because cordova isn't available in the browser. If you are new to Ionic development you can check how to Run your Ionic app in different environments.

Remember you can download all the source code of this Ionic example by clicking the GET THE CODE button from the beginning of this page.

Did you know that we recently released Ionic 5 Full Starter App? It's an ionic template that you can use to jump start your Ionic app development and save yourself hundreds of hours of development and design.

It is also ready to be a Progressive Web App and has lots of features you will love! Try the demo to see the magic!

ionic pwa
Get Ionic 5 Starter App

Next Steps

After having the google authentication working in your IonicApp you can focus on:

  • Build a Progressive Web App with Ionic Framework
  • Add Facebook Login to your Ionic App
  • Add Twitter Login to your Ionic App
  • Internationalize and Localize your Ionic app (Multilanguage)
  • Forms and Validations in Ionic
  • Prettifying your app using a theme or your design skills, taking advantage of the many possibilities that Ionic and Sass provide.

As you know we also sell beautiful ionic templates that you will find super useful as they save you hours of development, time and effort, while giving your projects a great design from scratch.

Why don’t you give a chance to our Ionic templates and apply this new knowledge?

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 cordova plugin to connect with Google native SDK
  • Step 3: Adding Login & Logout functionality
  • Next Steps

angular templates

Ionic Starters to jump start your app development:


Ionic 5 Full Starter App

Starters
- Ionic 5.x
$59 588

Ion2FullApp ELITE - The most complete Ionic 3 Starter App

Starters
- Ionic 3.x
$56 1193

Ion2FullApp PRO - Premium Ionic 3 Template

Starters
- Ionic 3.x
$47 532

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