In this post, you’ll learn how to implement Google login in your Ionic Angular Capacitor apps. We will also retrieve user name and profile photo to show after login. We will test the authentication on Web, Android and iOS.
Since Google login is applicable in a lot of app frameworks, it is possible you landed here by (SEO) mistake. If you are looking for Google login in
- Ionic Angular (Cordova) apps — Please check this post
- React Native — Please check this for Android and iOS
- Ionic React Capacitor Apps —Check this post
- Ionic Angular Capacitor Apps — Continue reading 🙂
As you can see from above, there are several options available for Hybrid app development these days, and it is easy to get confused between them. This post is focussed on Ionic framework with Angular as the front-end framework, and Capacitor as runtime and build environment.
Let’s see a brief intro to each of the included frameworks:
- Ionic
- Capacitor
What is Ionic ?
In short — If you create Native apps in Android, you code in Java/Kotlin. If you create Native apps in iOS, you code in Obj-C or Swift. Both of these are powerful but complex languages. With Ionic and Capacitor you can write a single piece of code for your app that can run on both iOS and Android (and web!), that too with the simplicity of HTML, CSS, and JS.
It is important to note the contribution of Capacitor in this. Ionic is a UI + functionality wrapper made up of HTML, CSS and JS. So, by default, Ionic cannot run as an app in an iOS or Android device. Capacitor is the build environment that containerizes (sort of) this Ionic web app and converts it into a device installable app, along with providing this app access to native APIs like Camera etc.
Capacitor — How is it different from Cordova ?
Capacitor is very similar to Cordova, but with some key differences in the app workflow
You might be familiar with the popular hybrid technology Cordova. So why are we using Capacitor? Cordova helps build Ionic web app into a device installable app. But there are some limitations of Cordova, which Capacitor tries to overcome with a new App workflow.
Capacitor is a cross-platform app runtime that makes it easy to build web apps that run natively on iOS, Android, Electron, and the web. Ionic people call these apps “Native Progressive Web Apps” and they represent the next evolution beyond Hybrid apps.
Here are few differences between Cordova and Capacitor
- Capacitor considers each platform project a source asset instead of a build time asset. That means, Capacitor wants you to keep the platform source code in the repository, unlike Cordova which always assumes that you will generate the platform code on build time
- Since platform code is a source asset, you can directly change the native code using Xcode or Android Studio. This give more flexibility to developers. We will do some similar changes for Google login as well.
- Capacitor has great PWA support in-built
- Capacitor CLI is locally installed, so different apps can have different Capacitor versions in your system
You can read more about Capacitor vs Cordova in this article by Ionic.
Plugins
Capacitor has its own set of plugins available in the core itself, or with @capacitor-community, but it can also support Cordova plugins. For Google login functionality, we’ll use the CapacitorGoogleAuth plugin by CodetrixStudio.
Capacitor plugins require a bit of configuration editing in Android and iOS files, but you don’t need any Android and iOS native expertise for that. Just follow along with the tutorial and you’ll find it very easy to implement Google login in Capacitor.
A word on Google authentication
We will use the CapacitorGoogleAuth plugin by CodetrixStudio to authenticate the user. Once the login is done, we receive user profile information in auth response itself. Hence, there is no need to fetch user’s profile information separately.
This Google Auth plugin supports 2 functions, across web, Android and iOS
- Login
- Logout
Also note that this plugin only helps you to login and logout using Google Auth. As you’ll see, the process of Google login involves creating a Firebase project etc. but this plugin does not connect your authenticated user directly to Firebase project.
In other words, there are two ways you can use Google login
- Confirm user’s authenticity from Google login, and then save the user info in your own Database. This is true if you already have a server and DB defined for your project
- Confirm user’s authenticity from Google login, and then save user info in the same Firebase project itself. It is a convenient and faster way. More about this in Step 2 and further
Structure of post
I always go step-by-step for readers of all experience level. If you know certain steps, feel free to skip them
Step 1: Create a basic Ionic Angular Capacitor app
Step 2: Create a Google project for authentication
Step 3: Setup Google Login Plugin and functions
Step 4: Prepare and Test on Web
Step 5: Build and Test your app on Android
Step 6: Build and Test your app on iOS
Let’s get started with Ionic Angular Capacitor Google login !
Step 1 — Create a basic Ionic Angular Capacitor app
Here’s my environment
- Node 14.x+
- Capacitor 3.0+
- Angular 12+
- NPM 7+
First you need to make sure you have the latest Ionic CLI. This will ensure you are using everything latest. Ensure latest Ionic CLI installation using
$ npm install -g ionic@latest
Creating a basic Ionic-React app is not much different or difficult from creating a basic Ionic-Angular app. Start a basic blank
starter using
$ ionic start IonNgCapGoogleLogin blank --type=angular --capacitor
The CLI options are pretty self-explanatory.
Run the app in browser using
$ ionic serve
You won’t see much in the homepage created in the blank starter. Let’s modify this page to include a button, icon and a title for login. Also, I have created a LandingPage, where the user is redirected after successful login. The user profile information in this page comes after login and single API call.
Attach Capacitor to existing app
Note: Unlike earlier, now you don’t have to attach Capacitor separately to your Ionic apps. When you run theionic start
command with--Capacitor
option, it attaches Capacitor to the app automatically.
If by change you forgot to attach Capacitor which creating the app, it can be attached to an existing Ionic app as well. To attach Capacitor to your existing Ionic app, run
$ ionic integrations enable capacitor
This will attach Capacitor to your Ionic app. After this, you have to init
the Capacitor app with
$ npx cap init
It will ask you the app name and ID. Give app name whatever you want. App ID is the domain identifier of your app (ex: com.example.app
). Note this ID as this will be required later when you create app in Google developer console. In my case, the ID is com.enappd.IonNgCapGoogleLogin
( too long, I know)
Step 2 — Create a Google project
To implement a Google login, you will need a Google app/project. A Google project can serve as a single point of control for your Google login, analytics, AdMob, push notifications, API keys for Map and several other services etc.
2.1 Create new project
Create a project in Google Developer console or create it in Firebase Console (recommended). Both consoles are essentially integrated with each other.
More details about creating a Firebase project can be found here.
2.2 Requirements for different project types
Web
As soon as you make a Google project in either Google Developer console or Firebase console, a web-client-ID
is automatically generated. For web-login, you only need this web-client-ID
More in Step 2.4 and Step 4.
Android
To implement Google Login in Android, we will have to create an Android app inside our Google project. In this Android app’s settings, we’ll get google-services.json
file. This files essentially contains the API keys and IDs for the project.
We’ll also have to attach SHA-1 key from our build system in our Google project’s Android app.
More in Step 5.
iOS
To implement Google Login in iOS, we will have to create an iOS app inside our Google project. In this iOS app’s settings, we’ll get agoogle-services.plist
file . This file essentially contains the API keys and IDs for the project.
For iOS we’ll also have to generate a URL scheme. More in Step 6.
2.3 Google-services.plist
In your Firebase console (of the same project), create a new iOS app. During creation process it will ask you the app bundle ID. Use the bundle ID you used to initialize Capacitor in section 2 (com.enappd.IonNgCapGoogleLogin
). In next step, download the google-services.plist
file.
If you already have an existing project, download the google-services.plist
from the Project Settings page.
2.4 Web-client ID
When you create a Google project, a web client ID
is automatically created. You can find this web-client ID in Google Developer console. Note that the web client ID says (Auto created by Google Service). You DO NOT need to create an Android or iOS app in the Google Project to create this web client ID.
If you create Android/iOS app in Firebase, you can get web-client ID from the downloadedgoogle-services.json
orgoogle-services.plist
file.
To use web-client ID on ionic serve
or on your website for web login, you need to make sure you include the origin URL in the Web Client ID’s settings
2.5 Web API Key
Required only for making a REST API call to get user profile info. Web API Key can be obtained from the Firebase console. It appears after you have at least once entered the Authentication module of Firebase console.
2.6 SHA-1 key
For web implementation of Google login, nothing is required in our Google project. But for Android implementation, we need to add Android app in the project. Also, make sure the app ID (com.something.something) you provide when making the Android app in Google project, is the same as your app ID. (Double check in capacitor.config.json
and capacitor.config.ts
)
Now create a SHA-1 key of your system. This key is specific to
- Your system (laptop/PC)
- Your app’s
.keystore
file
Use following commands to generate SHA-1 key
$ keytool -list -v -keystore <<YOUR_APP_KEYSTORE_PATH>> -alias <<KEYSTORE_ALIAS>> -storepass <<PASSWORD>> -keypass <<KEY_PASSWORD>>
All the above info (alias, keystore, passwords) should be same as the one you used when creating the Keystore file.
Add this SHA-1 key in Android App setting of your Google project
Step 3 — Setup Google Login Plugin and functions
To setup Google login in the app, we’ll do following things
4.1 Install CapacitorGoogleAuth plugin by CodetrixStudio.
4.2 Setup plugin functions for login
4.3 Navigate and Send data between two pages of the app
4.4 Sign Out
4.5 Detect already logged in users
4.1 Install Capacitor Google Auth plugin
Install the plugin using
$ npm i --save @codetrix-studio/capacitor-google-auth
Add the following info in your capacitor.config.json
Note: Capacitor 3.0+ usescapacitor.config.ts
by default. You’ll have to create thecapacitor.config.json
in root folder, and copy the content from the.ts
filem and add the following info. This is plugin specific
...
"plugins": {
"GoogleAuth": {
"scopes": ["profile","email"],
"serverClientId": "160012889513-qkxxxxxxxxxxxxxxxxxxxxxxxxkgubrp5ve.apps.googleusercontent.com"
}
}
...
serverClientId
is basically the web-client ID itself. Import the plugin in app’s pages using
import { GoogleAuth } from '@codetrix-studio/capacitor-google-auth';
4.2 Setup plugin functions for login
We have to setup few functions for Google Auth functionality
- init — GoogleAuth.init() — Initializes the plugin, required only in Web. This can be called at the page load. Avoid on device, or it will throw error.
- signIn—GoogleAuth.signIn() — Signs you in with a popup on web, and native functionality in device. This should be called after init(). The success of this function will given user profile data as response. Based on this response you can navigate user in your app.
- signOut — GoogleAuth.signOut() — Signs you out from Google. Based on success of this method, you can navigate user out of your app.
- refresh — GoogleAuth.refresh() — At app start (or at any point), it can check if you are already logged in. This can be helpful if you want to auto-login users who have logged in once.
I believe you can handle the HTML and CSS part of the pages yourself. The login code for Home.page.ts
looks like this
4.3 Enable routing between two pages of the app
The user data from Auth response can be sent to Landing Page using NavigationExtras
. Here’s what you need to add to home.page.ts
for navigating with data (where user
is the response object from GoogleAuth.singIn
)
import { Router, NavigationExtras } from '@angular/router';
....
export class HomePage {
constructor(private router: Router) { }
...
goToHome(user) {
let navigationExtras: NavigationExtras = { state: { user: user } };
this.router.navigate(['landing'], navigationExtras);
}
In landing.page.ts
, you can receive the data as follows
This way, you have logged in, and received the profile info of the user 🎉
4.4 Sign out
Once user is successfully logged in, we redirect user to Landing
page. And when user logs out, we want to come back to Home
page.
Sign out can be implemented with the following code on button click
signOut() {
GoogleAuth.signOut().then(() => {
this.router.navigate(['home']);
});
}
4.5 Detect already logged in user / Auto-login
In most of the apps, if you have logged in once, next time you open the app, you don’t have to login again. This can be done with our plugin as well.
We can detect already logged in user with GoogleAuth.refresh()
method, Here’s the implementation and the resulting full code for home.page.ts
So, on button click we check if user is already logged in using checkLoggedIn()
. If user is logged in, we send the user to Landing page with corresponding data. If not logged in, we go through the normal sign in route.
Once the user is detected as already logged in, we send the app user to Landing page with accessToken
. This accessToken
can then be used in a REST API call to get user’s profile info. Here’s the full code for landing.page.ts
including getting the user’s profile info with REST API Call.
Here, YOUR_WEB_API_KEY
is your web API key of Google project, which you obtained in Step 2.5
The https://www.googleapis.com/oauth2/v2/userinfo
end-point gives us the user’s profile info.
Note : I have used Capacitor Http plugin to make the API call. This is because this plugin can make API calls from all platforms while avoiding CORS and other issues. You can learn more on the plugin page
Step 4: Prepare and Test on Web
To implement Google Auth in web app with Capacitor, add this meta tag to head in index.html
file.
<meta name="google-signin-client_id" content="{your client id here}">
With all the above code in place, web Google login can be tested in ionic serve
itself. Here’s how it will work on browser
- Normal login -> Navigates to Landing page -> Signout -> Back to home page
- Normal login ->Navigates to Landing page | Refresh app on home page to simulate existing login on app start -> Takes you directly to Landing page
The response object user will output all auth info of the user as shown in following image
As you can see, you get all the required info in this response object. The response object obtained on the REST API call (as explained in Step 4.5) looks a little different. The profile photo comes under the property picture
instead of imageUrl
Step 5 — Build and Test your app on Android
Create and configure platform
To build the app on Android, run these commands
// Add android platform
$ npx cap add android
// Copy all changes to Android platform
$ npx cap sync
// Open the project in Android studio
$ npx cap open android
Also, add the following in your strings.xml
file in Android Project
<resources>
<string name="server_client_id">Your Web Client ID</string>
</resources>
Note: As of Capacitor 3.0, you do not need to add the plugin in the MainActivity.java
file
Avoid unimplemented methods
Build the app on Android device using Android studio. Make sure you detect the platform of device and NOT run GoogleAuth.init()
and GoogleAuth.refresh()
methods. These are currently not implemented in the plugin. Directly use GoogleAuth.singIn()
. Something like this needs to be added
import { Platform } from '@ionic/angular';
....
export class HomePage {
constructor(private platform: Platform, private router: Router) {
this.isWeb = !this.platform.is('android') && !this.platform.is('ios');
}
checkLoggedIn() {
if(this.isWeb){
//run web implementation with init() and refresh()
}
else{
// direct GoogleAuth.signIn()}
}
}
}
Make sure
- You have added SHA-1 key to your Google project’s Android app settings as per Step 2.6
- Your app ID is same as the one you added in Google project’s Android app (and in
capacitor.config.json
)
With these settings, your Google login should work fine in Android. Following GIF shows the login flow in my Android device.
Step 6 — Build and Test your app on iOS
Create and configure platform
To build the app on iOS, run these commands
// Add android platform
$ npx cap add ios
// Copy all changes to iOS platform
$ npx cap sync
// Open the project in XCode
$ npx cap open ios
- Place your downloaded
GoogleService.plist
inios/App/App
folder - Find
REVERSED_CLIENT_ID
from theGoogleService.plist
and add it as a URL scheme ininfo.plist
of Xcode
Make sure
- You have created iOS app in Google Project as per Step 2.3
- You have added
GoogleServices-Info.plist
inios/App/App
folder. Cross-check by checking in XCode - You have added required URL scheme as mentioned is last paragraph
Build the app on iOS device or Simulator using Xcode. You should be able to login via Google, and reach the inner page where you see the user information. Following GIF shows the login flow in my iPhone simulator
Conclusion
In this post you learnt how to implement Google login in your Ionic Angular Capacitor app. Social logins are very important part of your apps, as they make users trust your apps more. It is also easy to use, and users don’t have to remember any passwords. You can always link the Social logins with your server as well.
We also tested the Authentication on all three devices — Android, iOS and Web. This creates a complete set of devices a user can use with your app.
Google Login is a complex one among social logins. Make sure you follow all the steps very carefully.
Next Steps
If you liked this blog, you will also find the following blogs interesting and helpful. Feel free to ask any questions in the comment section
Ionic Capacitor
- Basic — Geolocation | Barcode & QR code | Facebook Login (Angular) | Facebook Login (React) | Icon and Splash | Camera & Photo Gallery | Debugging with browser|Theming in Ionic apps | Google Login (Angular)
- Advanced — AdMob | Local Notifications | Google Login | Twitter Login | Games using Phaser | Play music | Push Notifications
Ionic Cordova
- Taxi Booking App example with Ionic, Node, Express and MySQL
- Ionic Payment Gateways — Stripe with Firebase | Stripe with NodeJS | PayPal |PayPal with Braintree| Apple Pay | RazorPay
- Ionic Charts with — Google Charts | HighCharts | d3.js | Chart.js
- Ionic Authentications — Via Email | Anonymous | Facebook | Google | Twitter | Via Phone
- Ionic Features — Geolocation| QR Code reader | Pedometer| Signature Pad | Background Geolocation | Network Detection
- Media in Ionic — Audio | Video | Image Picker | Image Cropper | Sounds and Vibrations
- Ionic Essentials — Debugging with browser| Native Storage | Translations | RTL | Sentry Error Monitoring | Social sharing | PDF generation
- Ionic messaging — Firebase Push | Reading SMS | Local Notifications
- Ionic with Firebase — Basics | Hosting and DB | Cloud functions | Deploy App to Firebase | Firebase simulator
- Unit Testing in Ionic — Part 1 | Mocks & Spies| Async Testing
Ionic Capacitor Full App (Angular)
If you need a base to start your next Angular Capacitor app, you can make your next awesome app using Capacitor Full App
Ionic React Full App with Capacitor
If you need a base to start your next Ionic 5 React Capacitor app, you can make your next awesome app using Ionic 5 React Full App in Capacitor
Ionic Full App (Angular and Cordova)
If you need a base to start your next Ionic 5 app, you can make your next awesome app using Ionic 5 Full App
Top comments (0)