In this Ionic framework tutorial we are going to show you - step by step - how to integrate Google 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.
Benefits of adding Google Authentication to your Ionic app
- 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.
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 Ionic app that allows users to log in using their Google account. Once they log in, they will see a home page with their basic profile info.
Authentication is an essential part of most applications, and there are different approaches and strategies that you can take. The approach taken for any project depends on its particular application requirements. Let's explore some of these approaches.
Using your own API or Backend
If you already have an API or backend that handles user authentication, or if you like to have tight control over your 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 our production apps we use and recommend NestJS.
NestJS is basically a Node.js framework that enables you to easily build efficient and scalable server-side applications. The architecture is heavily inspired by Angular so if you are familiar with Angular, you will find very enjoyable to work with Nest. Implementing Authentication using Nest is very straightforward. Learn how to integrate NestJS to your Ionic App.
Using a Backend As A Service
If you don't want to take care of your own infrastructure and backend implementation, then there are a few BaaS (Backend as aService) 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 apps.
Using Social Providers
You can choose to provide authentication using well known social networks such as Facebook, Instagram, Twitter, Google, Github, etc.
We think that in these days, this is the best way to authenticate your users because it's easier and faster for them and also for you. Also, remember that providing a good user experience is a key factor, so providing a one click authentication will definitely add up to a good UX (unless you are building a banking application).
We have created a set of detailed Ionic Authentication tutorials to help you adding this functionality to your Ionic app.
So to define the scope of this post, in this tutorial we will explore how to add Google authentication to your Ionic app.
Each authentication option has its pros and cons, 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.
Update! From April 2020 onwards, if you want to publish your Ionic application on the Apple App Store, you also need to add Sign in with Apple. Why? Because they say so and they control their market (not happy with this? Build a PWA!).
The Apple guidelines states: "Apps that exclusively use a third-party or social login service (such as Facebook Login, Google Sign-In, Sign in with Twitter, Sign In with LinkedIn, Login with Amazon, or WeChat Login) to set up or authenticate the user's primary account with the app must also offer Sign in with Apple as an equivalent option." But, it also says: "Sign in with Apple is not required if: Your app exclusively uses your company's own account setup and sign-in systems."
If you need help starting with your Ionic App, I suggest you to take a look at Ionic Starter Template.
It will save you lots of development and design hours and it already has lots of useful features that you will love such as Google Login. Check some of the authentication screens available in the template.
There are different ways to integrate Google authentication into your Ionic app. However, not all of them use the native approach which uses the Google Application 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 enables log in with a Google account on iOS and Android. Using this plugin we will get the email, display name, given name, family name, profile picture url, and user id of the logged user.
For this Ionic example app you will need:
- An Ionic app where you will integrate this functionality. You can either use a Ionic blank app, or an existing one.
- Follow the setup steps from below for Android (to enable Google login on Android).
- Follow the setup steps from below 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:
There are some configurations you need to set in order to communicate your app with Google Authentication API. Please read each step carefully.
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">
iOS Configurations
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.
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".
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
.
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.
Android Configurations
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".
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
.
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. - 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.
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 for iOS and Android.
- Install Google Sign-In Plugin in your Ionic Framework 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 yourwebClientId
(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 yourwebClientId
and setoffline: 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); }) }
Native Storage
Native Storage 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 implementation
At this point you should have an Ionic application with Google log in and log out functionalities. To test the native implementation you need to test the application in a real device or in an emulator because Cordova isn't available on 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 tutorial by clicking the GET THE CODE button from the beginning of this page.
Did you know that we recently released Ionic 6 Full Starter App - PRO version? It's an Ionic PWA template that you can use to jump start your PWA development and save yourself hundreds of hours of design and development. Try it on your phone as a PWA.
Authentication is an essential part of most applications, and there are different approaches and strategies that you can take. The approach taken for any project depends on its particular application requirements. Let's explore some of these approaches.
In this post we explained how to add Google Sign In to an Ionic Framework application. We built a demo app that you can download and use for free to build your own Ionic application.
To add the log in functionality we used Google Sign In Cordova plugin. It enables a native log in both in iOS and Android apps.
If you have any issues or questions about this tutorial please leave a comment below.
If you want to keep learning Ionic Framework, I suggest you the following tutorials:
- Build a PWA with Ionic and Angular
- Add Facebook Login to your Ionic App
- Add Twitter Login to your Ionic App
- Build a Multi Language Ionic App
- Master Forms and Validations
At IonicThemes we are big fans of Learning by example, that's why all our Ionic tutorials include a complete and free Ionic code example that you can reuse in your Ionic projects.
We strive to create the best content for Ionic Framework, both tutorials and templates to help the Ionic community succeed. We work towards empowering developers to achieve a free life through coding. That's what motivates us at IonicThemes everyday.
Also, you can check out our detailed and professional Ionic Starter App crafted with love and dedication to help you create better apps and supercharge your productivity.
Liked this Ionic Tutorial?
Leave your comments below.