In this post, you will learn how to implement a Google authentication in Ionic 4 apps using Firebase 🔥.
We’ll cook a sample app 👨🍳 , where users can login using their Google account. After login, users can see their basic profile information on home page, and sessions are saved in Firebase.
Social logins — What and why
It’s helpful to use social sign-ins with Ionic for your users who would rather not create and remember another username/password combination. Instead, you can allow users to sign in with accounts they already own. You don’t need to store hashed passwords to compare, you don’t have to handle sending sign up emails, and you don’t need to reset passwords. The user’s chosen provider will handle all of this for you. Plus, in mobile apps, the Google login is automatically done with the pre-installed Google app.
Google login — What and why
There are several reasons why you should use a Google login in your app
- Ease of use — When a new user uses your app, only two buttons clicks are required to login using Google. In other scenario, user will have to type in an email/password and login
- No “forgot password” — When your app uses Google login, the user does not have to worry about forgetting password for your app’s login
- No “verify email” — If you use a custom-email authentication of your own, you will have to verify the email if it is a valid one or not. Google login will always have a valid email/phone number associated.
- Single solution — Google login can allow your users to use single login credentials across multiple devices
- Google integration — If your app uses Google authentication, you can use Google APIs inside your app as well. This can include fetching user tweets etc.
- Trust — Nowadays, people generally trust social logins moreover custom email logins. Social logins follows standard privacy protocols and hence are more reliable for information sharing
Ionic Authentication
Ionic framework has been around for around 5 years, and has been very popular among developers for its ease of usage over Swift / Java. Also in Ionic 4 you get to keep a single source code for both Android and iOS app. What more can a developer ask for!
Ionic 4 is the latest version (at the time of writing this post) of Ionic, and is much more reliable and robust than previous versions.
There are several ways of Authentication in Ionic 4 apps
- Social logins — Social logins are a popular and easy way of authentication in mobile apps. You must have seen Google, Facebook, Instagram logins in almost all the modern apps. Social logins are easy to use and more reliable for quick integrations.
- Create you own back-end — You can create your own back-end in Node.js, Go, Django or Ruby-on-rails, and connect your app authentication to your own back-end. This method is favored by developers who need full control over the user authentication. But this method is the most time taking one as well.
- Back-end as a Service (BaaS) — You can use pre-built BaaS platforms which allows easy integration of authentication in your apps. Basically, these platforms provide you a ready-made back-end, so you don’t have to make one on your own. Firebase, Parse, Back4App are some BaaS platforms.Firebase is the most popular among these for mobile apps, which we’ll study in next section
Firebase
Firebase is a Backend-as-a-Service (BaaS) platform. It started as a YC11 startup and grew up into a next-generation app-development platform on Google Cloud Platform. It is getting popular by the day because of the ease of integration and variety of functionalities available on it.
A lot of quick integrations are available with Firebase. Some of these are listed below:
- Real-time database
- Email Authentication
- Social logins
- In-app messages
- Push notifications
- Analytics
- Crashlytics
- Remote config
Firebase is quickly growing to become the most popular mobile app back-end platform.
Firebase Authentication Options
Firebase not only provides ready-made email authentication, but also provides authentication using a variety of social logins. You can see the authentication options available with Firebase
We will use Firebase to store user profile information once the Google login is done. This is the preferred method, as it is reliable for both apps and PWA.
Steps for Google authentication
We will follow these step-by-step instructions to create our Ionic 4 app with Google authentication
Step 1: Google Developer Console — Create your app
Step 2: Add your Platforms to Google
Step 3: Enable Google Sign-In in Firebase project
Step 4: Install the Cordova Google Plugin to connect your app with Firebase
Step 5: Authenticate Users using Google
Step 6: Store the Google auth IdToken and AccessToken in Firebase
Step 7: Use Firebase to auto-login the user
Step 8: Test your app on Android
Step 1: Google Developer Console
The first thing we need to do is to set up everything we’re going to need from Google to get our app working. We need to get:
- A
REVERSED_CLIENT_ID
from the Google developers console. - Enable Google sign-in inside the Firebase console.
- Take note of the credential so we can install the plugin.
To generate our credentials, we need to create both iOS and Android apps in the Google Developers Console (because we are using the awesome Ionic, which creates both iOS and Android from same code base 😎 ← woah I just italicized an emoji !!)
Log in with the Google account you use for Firebase (if it asks you to log in), and follow the instructions to create the app.
The first thing it’s going to ask you is the app name, as soon as you start typing it’s going to search for your Firebase apps, pick the one you linked to this project.
Note: You can create a Firebase project beforehand for this. Check out how to create a Firebase project and link to Ionic 4
In your project, go to API credentials and look for Web-Client ID. This will be used to get an idToken
or serverAuthCode
back from the Sign In Process, so we can save it in Firebase.
For first time you will get it after credentials process.For create credentials goto API credentials tab in Google Console.
And then — Create Credentials → OAuth Client ID.
And then it will ask you for application type and so select your application type here.
For iOS setup, you need to supply the bundle ID. This is the value in config.xml
which is set to io.ionic.starter
by default. Change that to whatever you like, and that will be your bundle ID.
Make sure you don’t leave it as the default value, it might conflict later on with other similar apps if you make your way to App stores.
The process for adding Google sign into the Android platform is almost identical, with one extra requirement. To get started, head to this link, and start creating your Android app.
It’s important to note that for building to Android (and also for using the cordova plugin) you will need to install the Android build tools version 19.1.0 or higher.
Acquiring the key 🔑
Once the build tools are installed and you’ve confirmed this, the keystore should be available to get the SHA-1 value we need for the Android part of the process. The keystore is used to hold the signing keys you use for the apps you build.
Run this command in the terminal to acquire the SHA-1 value need:
keytool -exportcert -list -v -alias androiddebugkey -keystore ~/.android/debug.keystore
Important: The keystores are different for debug and release versions. For testing purpose the debug.keystore (default) works good. But when you are going for production, make sure you repeat these steps with your release Keystore. Otherwise you’ll face random login errors
Add the SHA-1 value you got after running the previous command, to the above input.
After this step, head to this link, and add your Android project.
Make sure again that you have changed the config.xml ‘id’ value for your project so that it is no longer io.ionic.starter
.
Here package name is bundle id
After Adding application it will give you web client id
Which is also Reflected in OUR OAuth2.0 client Id’s
Now, click on edit button in front of highlighted Web Client ID as shown in pic above.
If you click the Web-client Id, you’ll get the Client Secret as well. Keep these safe for a later step.
Step 2: Add your Platforms to Google
In order for Firebase to work with both the native Android and iOS platforms, we’ll need to do two configurations for the app, each a little bit different.
iOS
In your Firebase console, create an iOS app
For iOS setup, you need to supply the bundle ID. This is the value in config.xml
which is set to io.ionic.starter
by default. Change that to whatever you like, and that will be your bundle ID.
Make sure you don’t leave it as the default value, it might conflict later on with other similar apps if you make your way to App stores.
After setup, you will get a GoogleService-Info.plist. Save this file to the root of the Ionic project folder. After performing these steps, your done! For iOS at least…
You should now see the following UI and have your Plist file downloaded and ready to use.
Android
The process for adding Google sign into the Android platform is almost identical, with one extra requirement. To get started, head to this link, and start creating your Android app.
It’s important to note that for building to Android (and also for using the cordova plugin) you will need to install the Android build tools version 19.1.0 or higher.
Acquiring the key 🔑
Once the build tools are installed and you’ve confirmed this, the keystore should be available to get the SHA-1 value we need for the Android part of the process. The keystore is used to hold the signing keys you use for the apps you build.
Run this command in the terminal to acquire the SHA-1 value need:
keytool -exportcert -list -v -alias androiddebugkey -keystore ~/.android/debug.keystore
Important: The keystores are different for debug and release versions. For testing purpose the debug.keystore (default) works good. But when you are going for production, make sure you repeat these steps with your release Keystore. Otherwise you’ll face random login errors
Step 3: Enable Google Login in Firebase.
Now that everything is set up on Google side, we need to go into our Firebase console and enable Google authentication for our app.
To enable Google , you’ll need to go to your Firebase Console and locate the app you’re using (or create a new Firebase project)
Once you’re inside the app’s dashboard, you’re going to go into Authentication > Sign-In Method > Google and click the Enable toggle.
And save your web client Id and Secret in Your Firebase app.
Step 4: Install the Google Cordova Plugin
In this step we will install the Cordova plugin in our Ionic app.
For that, open your terminal and type
$ ionic cordova plugin add cordova-plugin-googleplus --save --variable REVERSED_CLIENT_ID=myreversedclientid --variable WEB_APPLICATION_CLIENT_ID=mywebapplicationclientid
You’ll need to replace the values in REVERSED_CLIENT_ID with your real credentials. You can find both of these inside your Google Developers Dashboard.
It’s bit clumsy to work with Cordova plugin so ionic team created Ionic Native, which is a wrapper for the Cordova plugins so we can use them in a more “Angular/Ionic” way.
So now we will open our terminal and try this command to install Google package from Ionic Native
$ npm install --save @ionic-native/google-plus
Initialize Firebase in your app
To start off, let’s create an Ionic Application. You can either use our Ionic 4 full Authstarter or you can create your own Ionic 4 app from scratch. This app contains all type of Authentications using Firebase.
To learn more about how to create Ionic app from scratch, read How to create Ionic 4 app from scratch for beginners
Also, we need to install @angular/fire npm module, which actually connects the Firebase functionality to Ionic app. To install the module, run
$ npm install firebase @angular/fire --save
Also, include environment
,AngularFireModule
and AngularFireAuthModule
in app.module.ts
Import environment and AngularFire modules in app.module.ts
Notice that Firebase is initialized in your app with
AngularFireModule.initializeApp(environment.config)
where environment.config
is the Firebase config you picked from Firebase project.
Connect you app with Firebase
Details of this step can be found in our blog How to integrate Firebase in Ionic 4 apps
To connect you app to Firebase, you first need a Firebase project. From the project you will pick up you Firebase config parameters and include them in an environment file at the root of your Ionic project. The environment file will look like following
You can create two different environment files for development and production environments.
Step 5: Authenticate Users.
The first thing we need to do is to get the authorization idToken and Access Token from Google. To do that, we need to import Google plugin from Ionic Native and ask our user to log in. The import and login functions will be as follows
home.page.ts for Google login
This function will give you Google idToken and AccessToken and from this tokens we will login user to Firebase app.
Step 6 — Store the Google auth tokens in Firebase
In previous step, the authentication is done via Google app on your phone. Once logged in, you will receive a idToken and Accesstoken in response. This info will be used to connect to Firebase in the success
of Google login
So, in short we have logged in via Google, and created a Firebase user using the Google id token and access Token . From now on, Firebase can handle your login / logout in the app. After we store the token in Firebase, we navigate to Profile page.
Get user profile info
In Profile page, we will get the profile information of the user using Firebase Auth Module again.
profile.page.ts — Getting user profile and Logout function
Logout function
Since Firebase is now handling the login / logout, the logout function in profile.page.ts
page will look like following
Step 7 — Use Firebase to auto-login the user
At this point we have covered following points
- Login with Cordova Google plugin
- Pass Google idToken, accessToken to Firebase
- Fetch user profile info via Google plugin
- Logout using Firebase
Now, if the user does not logout and leave the app, we want the app to auto-login the next time user starts the app. For this, we will use Firebase’s onAuthStateChanged
function at the start of the app. If there is a valid user logged in, it will return user’s information. Our app.component.ts
file will look like following
Conclusion
In this post you learnt how to implement Google login in your Ionic 4 app. You also learnt how to auto-login your user using info stored in Firebase. The Firebase integration done for Authentication, can be used for various purposes like Database CRUD operations, push notifications, analytics etc.
Next Steps
Now that you have learned the implementation of Firebase Email auth in Ionic 4, you can also try
- Anonymous logic in Ionic 4 using Firebase
- Twitter login in Ionic 4 with Firebase
- Facebook login in Ionic 4 with Firebase
- Ionic 4 PayPal payment integration — for Apps and PWA
- Ionic 4 Stripe payment integration — for Apps and PWA
- Ionic 4 Apple Pay integration
- Translations in Ionic 4
- Geolocation in Ionic 4
- QR Code and scanners in Ionic 4 and
If you need a base to start your next Ionic 4 app, you can make your next awesome app using Ionic 4 Full App. This is the most powerful Ionic 4 starter available today.
This blog was originally posted on enappd.com
Top comments (0)