Ionic Firebase Authentication Tutorial

What is Firebase?

First of all, do you know what is Firebase?. Firebase is a popular tool that helps you build apps fast, without managing infrastructure. It offers lots of services to help your app grow. It's built on Google infrastructure and can scale automatically, so you don’t have to worry about scaling your own servers. It includes 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. We have another tutorial covering Firebase Database usage in Ionic Framework Apps.

Popularity for Firebase in Ionic and Angular apps has been growing a lot, and in this firebase authentication example, we will explain you everything about Ionic Firebase Authentication.

Ionic Authentication Options

In this ionic tutorial we’ll learn how to configure a firebase application to enable an ionic 3 application to log in with both Email and Password and social providers such as Facebook, Twitter and Google.

Before I start with the technical part, I’d like to explain the benefits of adding social authentication providers to your app, made with Ionic Firework, and explore every possible option.

Why adding Social Authentication to your Ionic App will benefit you and your users?

  • Improve conversions: Help people log in your ionic 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 users control over the info they share with your ionic app.

  • Access profile info: such as picture, gender, age, name, without having to ask for it.

Authentication is a key component for your Apps, and you can take various approaches. Let's see some of them.

The handcrafted way (using your own API or 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 use a token based authentication.

The BaaS way

If you don’t want to have to deal with your own infrastructure and backend implementation, then there are a few BaaS (Backend as a Service) options.

In this Firebase Authentication Tutorial we’ll explain how to use Firebase as an authentication provider for your Ionic Apps.

Firebase is a great service that will help you build your app’s backend with ease. Firebase has very useful services to build mobile apps. It offers cool features like analytics, user authentication, cloud messaging, realtime database, and notifications. It’s worth mentioning that it’s owned by Google.

Recently we’ve been working on many Firebase tutorials related to Ionic Apps because we think Firebase is a great option for those developers who want to start building Ionic Apps right away without having to pay attention to the backend. Our most recent Ionic + Firebase tutorial is about Building a Complete Ionic Firebase App step by step.

The Social way

You can chose to provide authentication using well-known social networks such as Facebook, Instagram, Twitter, Google, etc. We think that nowadays adding social login providers to your ionic app is a must, so we’ve created a set of tutorials to help you with this:

Each option has it’s benefits, and of course you can mix them and offer an even more complete solution and experience to your users. It’s very common to see different ways of authenticating users within an app.

In Ion2FullApp ELITE - The most complete Ionic 3 Starter App you will find a ready-made example of how to use Firebase Authentication inside a real Ionic Framework Application. Using a template will save you lots of development time and will give your app a proffesional look.

These are some of the Ionic pages you can find in the Firebase Integration section of Ion2FullApp ELITE.

The functionalities of this firebase integration include: authentication with different providers, feed with search filters, profile page with image handling (for profile picture) and all the CRUD operations.

Ion2FullApp Ionic Firebase Authentication
Ion2FullApp Firebase Ionic
Ion2FullApp Firebase CRUD

Firebase Authentication for your Ionic App

Now that we’ve learned a little more about the possible authentication options for our ionic framework apps, let's get into the world of Firebase.

Inside the Firebase platform, there are different authentication options, which we’ll explore. In this ionic firebase tutorial we’ll be implementing the old-school authentication method, by configuring user and password, and we’ll also see how to implement auth by using the Firebase Social Providers.

That way we’ll teach you a Social + BaaS approach using Firebase platform.

To implement the logins with social providers, we’ll use the native Ionic Framework plugins, which we know by the name of Ionic Native.

Ionic Native is a TypeScript wrapper for Cordova/PhoneGap plugins that make adding any native functionality you need to your Ionic mobile app easy. Ionic Native wraps plugin callbacks in a Promise or an Observable, providing a common interface for all plugins and ensuring that native events trigger change detection in Angular. You can learn more about Ionic Native by reading the official documentation.

For communication between the Ionic app and the Firebase database we’ll use the angularfire2 plugin. AngularFire is the official library for Firebase and Angular.

Setting up Firebase Authentication

Create the Ionic App

To start with this firebase authentication example, we’ll create an application with Ionic Framework. You can download the code of this example for free or you can create your own app from scratch.

This is the application that we’re going to build in this ionic firebase tutorial:


Firebase Authentication Tutorial
Firebase Authentication Tutorial

To install the angularfire2 plugin that we mentioned in the introduction, we must run the following command in our console.

npm install firebase angularfire2 --save

Create the Firebase App

Once we’ve installed the plugin that we’re going to use to make our Ionic app communicate with Firebase, we’ll create a new project in Firebase. To create your project, go to the firebase console, where you’ll see the following menu:

setting up firebase authentication

Click on "Add Firebase to your web app" to see the credentials of your new Firebase application. We’ll specify these credentials to tell our Ionic application to communicate with our Firebase application.

setting up firebase authentication

The next step will be to add these credentials to our ionic project. To do so, we’ll use the environment.ts file, which is located in src/environments/ and we’ll add the following:

export const environment = {
 production: false,
 firebase: {
   apiKey: "YOUR_API_KEY",
   authDomain: "YOUR_AUTH_DOMAIN",
   databaseURL: "YOUR_DATABASE_URL",
   projectId: "YOUR_PROJECT_ID",
   storageBucket: "YOUR_STORAGE_BUCKET",
   messagingSenderId: "YOUR_SENDER_ID"
 }
};

Keep in mind that you have to replace the constants with your own values.

We’re now ready to begin with the login implementation.

Firebase Login with Social Providers in Ionic

To enable authentication with social providers in our firebase app, we need to go to the Authentication section (from the firebase console) as shown in the image and enable the necessary methods:

setting up firebase authentication in ionic

Add Firebase Facebook Login

To integrate Facebook Authentication, we must first create a Facebook application which we’ll then connect to our ionic app. To create it, we must go to the Facebook developer console and follow the steps.

Once you’ve created your Facebook application, you’ll get an APP ID and a SECRET KEY APP, which you’ll use briefly.

We’re going to implement the Facebook native login, this means that if the user has the Facebook app installed in his or her cell phone, they will be asked for the same authentication credentials. To add this functionality, you need to install the Facebook Connect plugin and we’ll do so by running the following command:

ionic cordova plugin add cordova-plugin-facebook4 --variable APP_ID="123456789" --variable APP_NAME="myApplication"

npm install --save @ionic-native/facebook

If you need help with these steps, you can read Add Facebook Login to an Ionic 3 App where you’ll find how to create the Facebook Application in detail.

Now we return to the Firebase console and go to the Authentication section where we’ll enable the Facebook option. As you can see, you need to add the APP ID and APP SECRET KEY.

facebook firebase authentication

Once this Facebook Authentication option is enabled, an "OAuth redirect URI" will be generated automatically, which you must include in your Facebook application as shown in the following image:

facebook firebase authentication with ionic

Before being done with Facebook, we must add an extra configuration depending on the platform on which you want to distribute your application:

For Android:

If you haven’t already done so, add Android platform to your ionic app by running:

ionic cordova platform add android

We need to complete the following inputs to allow the Facebook application to connect with our Android application made with Ionic framework:

set up facebook firebase authentication

Google Play Package Name: Find your package name in platforms/android/AndroidManifest.xml. In the following example the name would be: “io.ionic.ionic3FirebaseLogin”

<manifest android:hardwareAccelerated="true" android:versionCode="1" android:versionName="0.0.1" package="io.ionic.ionic3FirebaseLogin" xmlns:android="http://schemas.android.com/apk/res/android"/>
		

Class Name: com.facebook.FacebookActivity

Key Hashes: each person has to generate his or her own hash key and for that you must do the following.

If you’re developing on OS X, run:

keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore | openssl sha1 -binary | openssl base64

If you’re developing on Windows, run:

keytool -exportcert -alias androiddebugkey -keystore %HOMEPATH%\.android\debug.keystore | openssl sha1 -binary | openssl base64

For IOS:

If you haven’t already done so, add iOS platform to your ionic app by running:

ionic cordova platform add ios

We need to complete the following inputs to allow the Facebook application to connect with our iOS application made with Ionic framework. You only need the Bundle ID, the others are optional.

firebase authentication with facebook

Bundle ID: It’s found in config.xml inside the widget tag. In the following example it would be: “io.ionic.ionic3FirebaseLogin”

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

Add Firebase Google Login

The first thing we need to do is create a new project in the Google Developer Console. Then we must make some configurations to be able to add google native login to our ionic 3 application.

It’s time to install Google Plus cordova 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:

ionic cordova plugin add cordova-plugin-googleplus --variable REVERSED_CLIENT_ID=myreversedclientid

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

myreversedclientid is your REVERSED_CLIENT_ID and should look like this: com.googleusercontent.apps.uniqueId. You can find the uniqueId for iOS in credentials on client IDs section.

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

Make sure you execute the keytool steps explained here to get SHA1 or the authentication will fail.

Hint: if you’re asked for a password you can use: android

Finally, we must enable the login method with Google (in the authentication section) and if you haven’t obtained the SHA1 configuration, follow the instructions shown in the following image.

google firebase authentication

Add Firebase Twitter Login

Using Twitter's Fabric SDK, you can enable Single Sign On with your Android and iOS apps. To use Fabric, you’ll need to create an account.

To get the API key, log in to your Fabric account and then go to this link.

You will see your API keys like in the following image:

twitter firebase authentication

Configuring Twitter as a login provider for our Ionic app has a similar process to that of Facebook. To implement the Twitter login, we need to create a Twitter application in Twitter application management console. Just follow the steps form the Twitter console to create a new application.

Once your Twitter application is created, you’ll get your API ID and API SECRET KEY. Keep them at hand because you’ll use them briefly. If you need help with this step you can read Add Twitter Login to an Ionic 3 App where you’ll find detailed instructions on how to create a Twitter App.

After you have your Fabric API key it’s time to install the plugin into your app. Follow these steps to get this done:

  • Execute the following command on the terminal changing the variables with your own values:
    • Replace fabric_API_key with your FABRIC_KEY
  • ionic cordova plugin add twitter-connect-plugin --variable FABRIC_KEY=fabric_API_key --save

  • npm install --save @ionic-native/twitter-connect

Now we’ll go back to the authentication section in the Firebase console. We’re going to enable the Twitter option and at this moment we enter the API KEY and API SECRET KEY.

twitter firebase authentication

Once the Twitter login is enabled, a callback URL will be automatically generated, which must be added to the Twitter application as shown in the following image.

twitter firebase authentication with ionic framework

Add Firebase Login to your Ionic app

After having created all the corresponding applications to enable login with social providers in our ionic framework app, we’ll proceed to explain how our ionic app communicates with social apps.

Ionic Authentication Service

In this firebase authentication example we created a service with methods that will allow us to log in, create a new account and log out with various Firebase providers. We call this service AuthService and you can find it in src/pages/core/auth.service.ts .

The entire authentication logic will be in this service. This allows us to create components that don’t need to use any authentication logic and will help us simplify our components.

In other words, our AuthService will do most of the work and will be an intermediary between our Ionic and Firebase application.

In AuthService we’ll import the Firebase libraries as follows (this is possible because at the beginning of this Firebase Authentication Tutorial we installed angularfire2 in our Ionic project):

import { AngularFireAuth } from 'angularfire2/auth';
import * as firebase from 'firebase/app';

Then we add the following to the constructor to be able to use the methods of the AngularFireAuth class.

constructor(public afAuth: AngularFireAuth){}

Implement Social Native Login

In our AuthService we’ll be able to login with social networks using Firebase. As stated in the introduction, we’re going to implement the native login as we believe it provides a much better user experience than the javascript login.

Please note that the native login is only possible in mobile devices (or emulators) but not in the browser. So if you test this ionic example app in your browser you will see that the social logins are implemented with a pop up.

As an example, we’ll show you how to login with Facebook. Allow me to remind you that you can find this code in src/pages/core/auth.service.ts:

doFacebookLogin(){
   return new Promise<FirebaseUserModel>((resolve, reject) => {
     if (this.platform.is('cordova')) {
       //["public_profile"] is the array of permissions, you can add more if you need
       this.fb.login(["public_profile"]).then((response) => {
         const facebookCredential = firebase.auth.FacebookAuthProvider.credential(response.authResponse.accessToken);
         firebase.auth().signInWithCredential(facebookCredential)
         .then((user) => {
           resolve()
         });
       },(err) => {
         reject(err);
       });
     }
     else{
       this.afAuth.auth
       .signInWithPopup(new firebase.auth.FacebookAuthProvider())
      .then((user) => {
         resolve()
      })
    }
  })
}

Once the user is authenticated with any of the providers, they’ll be able to leave that session (commonly known as Log Out) and will be redirected to the login page.

doLogout(){
   return new Promise((resolve, reject) => {
     if(firebase.auth().currentUser){
       this.afAuth.auth.signOut()
       resolve();
     }
     else{
       reject();
     }
   });
}

You can see the Twitter and Google login methods in the AuthService.

After a user accesses our application through one of these social providers, we’ll see their information in our firebase console.

Email and Password Authentication with Firebase and Ionic

To allow our users to also authenticate themselves with a username and password in addition to social networks, we must follow these steps.

First of all we must enable the login method with email/password in the firebase console.

You’ll need to have a basic knowledge about Forms, to create a login page with the email and password fields.

We return to the auth.service.ts service where, as we already mentioned, we can find all the methods related to authentication. We’ll implement a doRegister() method which uses the data the user entered in the form.

It’s important to know that firebase performs some validations, like if the password has at least 6 characters or if the email is already associated with another account.

doRegister(value){
 return new Promise<any>((resolve, reject) => {
   firebase.auth().createUserWithEmailAndPassword(value.email, value.password)
   .then(res => {
     resolve(res);
   }, err => reject(err))
 })
}

The login method is similar, so I won’t repeat the implementation, so the firebase auth tutorial won’t be too long. You can see the code in the auth.service.ts file.

After a user accesses our application using email and password, we’ll see their information in our firebase console.

Keep Learning Ionic and Firebase

In this Ionic Firebase Authentication tutorial we learned to use the most common login methods, both social (Facebook, Twitter, Google) and using email/password. We also included the logout functionality.

If you want to learn more about Firebase Integration in Ionic Framework apps you can continue with the following tutorials:

If you are working on an Angular website, check Firebase Authentication with Angular. It's an Angular tutorial that explores how to setup an email/password as well as social login authentication workflows for Angular apps using AngularFire2 library.

If you wish to keep learning about Firebase stay tuned for upcoming tutorials in which I’ll write about how to make CRUD operations using Cloud Firestore. You can subscribe to our newsletter to get notifications when new ionic tutorials are released.

I hope this ionic firebase tutorial was helpful. If you have any questions don’t hesitate to leave a comment on the section below.

Would you like to keep learning Ionic Framework? Find dozens of ionic framework tutorials in our tutorials section.