Most apps need to know the identity of the user who is using it. Knowing a user's identity allows an app to securely save user data in the cloud and provide a personalized experience across all user's devices.

In this Ionic + Firebase tutorial you will learn how to create an Ionic Framework Application with Firebase Authentication. We will show you how to configure both the Firebase and the Ionic 5 App to enable authentication with social providers such as Google, Facebook and Twitter and also with Email and Password.

As an example we are going to build a simple Ionic Framework application that allows users to log in and log out using all the previously mentioned authentication options. Once they log in, they will see a profile page with their basic profile info taken from the authentication provider.

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 such as Authentication. It's built on Google infrastructure and can scale automatically, so you don't have to worry about scaling your own servers. Furthermore, 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. Learn more about Firebase Database usage in Ionic Framework Apps.

Firebase Authentication provides backend services, easy-to-use SDKs, and ready-made UI libraries to authenticate users to your app. It supports authentication using passwords, phone numbers, popular identity providers like Google, Facebook and Twitter, and more.

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.

In this Ionic 5 tutorial you will learn how to configure a Firebase application to enable an Ionic 5 application to log in with both Email and Password and social providers such as Facebook, Twitter and Google.

You will learn how to create the following app. Remember you can download all the source code of this Ionic 5 Firebase app by clicking the GET THE CODE button from the beginning of the page.

Ionic Firebase auth
Ionic Firebase auth
Ionic Firebase auth

Before we start with the technical part, I'd like to explain the benefits of adding social authentication providers to your app and explore some possible options.

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

  • Improve conversions: Help users sign in to your application quickly without having to remember another username and password.

  • One login across every device: Make it easy for users to sign in and access their information across multiple platforms and devices.

  • Build a trusted relationship: Give users control over the information they share with your app.

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

Authentication is a key component for your applications, and you can follow various approaches. Let's mention some of them.

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 developers 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.

Using a Backend as a Service

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

In this Ionic 5 Firebase Authentication tutorial we are going to explain how to use Firebase as an authentication provider for your Ionic Framework 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, real-time database, and notifications. It's worth mentioning that it's owned by Google.

In our blog we've many Firebase + Ionic tutorials because we think Firebase is a great option for those developers who want to start building Ionic Framework apps right away without having to deal with their own infrastructure. Also, our most recent Ionic Firebase tutorial is about Building a Complete Ionic Firebase App step by step.

Using Social Providers

You can also choose to support authentication using well-known social networks such as Facebook, GitHub, Twitter, Google, etc. We think that nowadays adding social sign in providers to your Ionic apps is a must, so we've created a set of tutorials to help you with this:

Each option has its benefits, and of course you can mix them and offer a better user experience to your users. Nowadays, it's very common to see different ways of authenticating users within an application.

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."

In Ionic 6 Full Starter App — PRO version you will find a ready-made example of how to use Firebase Authentication in a real Ionic Framework app. Using a template like this will save you tons of development and design hours and will give your app a professional look and feel.

This Ionic Firebase Starter App also includes an advanced Firebase CRUD integration with search filters and nested relations.

Ionic 5 Firebase Authentication
Ionic 5 Firebase App
Ionic Firebase App

If you are building an Ionic Angular app, the easiest way to authenticate your users with Firebase is to handle the sign-in flow using AngularFire and the Firebase Authentication web library.

However, if you plan to build native iOS and Android apps, there is some extra work that needs to be done.

In this Ionic Firebase authentication tutorial we use Ionic Capacitor to build our native projects.

Firebase web library needs the app to be served from origins with the file:// or ionic:// scheme. This is required so that Firebase Auth can properly handle signInWithRedirect and signInWithPopup operations (we will see more about this later). Firebase Auth will treat localhost origins as web-based browser apps.

Capacitor apps are hosted on a local HTTP server and are served with the http:// protocol, so there is no match between these protocols. For this reason, we need to use the native SDKs to perform social authentication from our native (iOS and Android) apps.

Because of this, there are some extra configurations you need to do in order to support Firebase authentication from your iOS and Android native apps with Capacitor.

In the demo app we built for this tutorial we will only cover the web implementation. This means that everything will work smooth from your browser. However, if you try this demo Ionic app from your device or emulator you will get the following error:

{
 "code": "auth/operation-not-supported-in-this-environment",
 "message": "This operation is not supported in the environment this application is running on. "location.protocol" must be http, https or chrome-extension and web storage must be enabled."
}

So, after mentioning this issue, let's be clear about the scope of this tutorial. First, we will explain how to configure everything, so you can have an Ionic 5 app with Firebase authentication from the browser, like in the demo app we provide for free in this tutorial.

To be able to have Firebase authentication functionality in your native apps built with Capacitor there some extra works that needs to be done. In this tutorial, we will also go through these configurations, however, the demo app provided doesn't include these functionalities.

If you want a ready-made example of how to use Firebase Authentication in Ionic 5 with Capacitor configurations for iOS and Android, check Ionic 6 Full Starter App — PRO version. We spent many hours configuring and testing everything so that you don't have to. Learn more about the starter app and try it on your devices.

Now that we have discussed a bit about possible authentication options for our Ionic framework apps, let's get into the topic of this tutorial: Firebase Auth in Ionic Apps.

This section is all about configurations, and there are some tips and tricks that you need to be aware of.

Create an Ionic Angular App

This tutorial is about adding Firebase auth to your Ionic Angular app so at this point you can imagine that you will need an Ionic Angular App!
You can create a new Ionic 5 app from scratch using the Ionic CLI or you can download for free the code of the example app we built for this specific tutorial. To do so just go to the beginning of this page and click the GET THE CODE button.

In order to connect our Ionic Angular application with Firebase we are going to use AngularFire plugin.‌ This is the official Angular library for Firebase. To install the plugin we have to run the following command in our Ionic project:

npm install firebase @angular/fire --save

Create a Firebase App

Now, you need a Firebase project to connect with this Ionic app. Go to Firebase console and start a new project (or select an existing one). Once you have created the Firebase project you will be redirected to the following menu:‌

setting up Firebase authentication

Click on "Add Firebase to your web app" to see your new Firebase application's credentials. We will use these credentials so our Ionic app knows how to communicate with our Firebase app.

setting up Firebase authentication

The next step will be to add these credentials to your Ionic project. To do so, go to the environment.ts file, which is located in src/environments/ and 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 are now ready to begin with the sign in implementation.

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 below image and enable the desired methods:

setting up Firebase authentication in Ionic

Add Firebase Facebook Login

To integrate Facebook Authentication, we must first create a Facebook application which we will then connect to our Ionic app. To do so, go to the Facebook developer console and follow the wizard to create a new app.

Once you have created your Facebook application, you will get an APP ID and a APP SECRET KEY. Add these credentials in your Firebase project under the Facebook Authentication option.

Facebook Firebase authentication

As you can see in the previous screenshot, when you enable Facebook as an authentication provider, a "OAuth redirect URI" will be generated automatically. You need to add this URI in your Facebook application as shown in the following image:

Facebook Firebase authentication with Ionic

Add Firebase Google Login

You can let your users authenticate with Firebase using their Google Accounts. Enable Google Sign-In in the Firebase console as shown below:

Google Firebase authentication

Add Firebase Twitter Login

To integrate Twitter Authentication, we need to create a Twitter application which we will then connect to our Ionic app. The process is similar to Facebook.

First, create a Twitter developer application and get your app's OAuth API key and API secret.

Now go back to the authentication section in the Firebase console and enable the Twitter option. Enter the credentials from your new Twitter App as shown below.

Twitter Firebase authentication

Once the Twitter Sign In is enabled, a callback URL will be automatically generated by Firebase. Add this Authorization callback URL in your app's settings page on your Twitter app's config.

Email/Password Sign In

You can use Firebase Authentication to let your users authenticate with Firebase using their email addresses and passwords, and to manage your app's password-based accounts.

Just enable Email/Password option in the Firebase console as shown below:

email Firebase authentication
Ionic templates

As mentioned at the beginning of this tutorial, if you plan to build native iOS and Android apps, there's some extra work that needs to be done in order to provide Firebase authentication with social providers.

Luckily, an Ionic community member created Capacitor Firebase Auth Plugin that handles the authentication on Native layer and propagate the token to the web view layer. After the sign-in process completes, the user will be signed in within both tiers.

Native projects configurations

There are some configurations you need to do in order to support Firebase authentication from your iOS and Android apps. Everything is explained here, so make sure to follow these guides carefully.

First, make sure you created the social apps as explained in the previous section.

Second, you need to create the native projects in your Firebase Console by following these steps:

When creating your Android project (or you can also do it later) you need to specify your app's SHA-1 fingerprint. You can do so from the Settings page of the Firebase console. See Authenticating Your Client for details on how to get your app's SHA-1 fingerprint.

Google Native Sign In Configurations

After creating your Android and iOS projects in Firebase you will get a google-services.json file for android and GoogleService-Info.plist for iOS.

native apps Firebase config

Download these files. For iOS open your Ionic project on Xcode and this the GoogleService-Info.plist into your project in App/App like this:

Xcode config files

For Android add google-services.json in your android project in android/app like in the image below:

android config files

Facebook Native Sign In Configurations

If you plan to build your Ionic app for iOS and/or Android you need to add those platforms to your Facebook App. To do this go to Settings > Basic menu and add both iOS and Android platforms.

For iOS:

For iOS platform complete the following details using your own Bundle ID. You can find this ID in ios/App/App/capacitor.config.json

{
  "appId": "com.ionicthemes.ionic5fullapp",
  ...
}
Capacitor Firebase authentication

For Android:

In Android platform complete the following details using your own Google Play Package Name. You can find this ID in android/app/src/main/AndroidManifest.xml under the manifest tag.

<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.ionicthemes.ionic5fullapp">

Then generate a key hash and add it in the Key Hashes input.

Capacitor Firebase authentication

Twitter Native Sign In Configurations

Go to your Twitter developer application created in the previous section and add the following callback URLs, in addition to the one we had previously added.

  • twitterkit-[YOUR_API_KEY]://
  • twittersdk://

Remember to rename [YOUR_API_KEY] with your own key.

After creating all the corresponding applications and configuration to enable sign in with social providers, we can proceed to explain how our Ionic 5 app communicates with Firebase.

Firebase Authentication Service

In our Firebase authentication example app we created a service with methods that will allow us to sign in, sign up and sign out with various Firebase providers. We named this service FirebaseAuthService and you can find it in src/app/firebase-auth.service.ts. Remember to get the code of the demo app included in this Angular Firebase tutorial.

All the code to communicate with Firebase can be found in this service. This allows us to create components that don't need to use any authentication logic and will help us to simplify our components.

In other words, our FirebaseAuthService will do most of the work and will be the intermediary between our Ionic and Firebase applications.

Let's see how to set up our @NgModule for the AngularFireModule. Remember that at the beginning of this tutorial we installed the AngularFire plugin? So now you will see how to use it.

Open src/app/app.module.ts, inject the Firebase providers (in our case we just need AngularFireAuthModule), and specify your Firebase configuration as follows:

@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    IonicModule.forRoot(),
    AppRoutingModule,
    AngularFireModule.initializeApp(environment.firebase),
    AngularFireAuthModule
  ],
  providers: [
    StatusBar,
    SplashScreen,
    FirebaseAuthService,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

Now, in our previously mentioned FirebaseAuthService we will inject AngularFireAuth as follows:

import { AngularFireAuth } from '@angular/fire/auth';
...
constructor(public angularFire: AngularFireAuth) {
...
}
Ionic templates

Firebase Authentication from Web

You can prompt your users to sign in with their social accounts (Twitter, Facebook, Google) either by opening a pop-up window or by redirecting to the sign-in page. The redirect method is preferred on mobile devices. In this tutorial we included both options, so you can choose which one you prefer.

As stated in the introduction, in this angular firebase tutorial we are going to implement the web sign in. If you want to get an Ionic 5 app with native sign in out of the box please check Ionic 6 Full Starter App.

So, in FirebaseAuthService you will find the following methods:

signInWithEmail(email: string, password: string): Promise<auth.UserCredential> {
  return this.angularFire.signInWithEmailAndPassword(email, password);
}

signUpWithEmail(email: string, password: string): Promise<auth.UserCredential> {
  return this.angularFire.createUserWithEmailAndPassword(email, password);
}

signInWithFacebook() {
  const provider = new auth.FacebookAuthProvider();
  // const scopes = ['user_birthday'];
  return this.socialSignIn(provider.providerId);
}

signInWithGoogle() {
  const provider = new auth.GoogleAuthProvider();
  const scopes = ['profile', 'email'];
  return this.socialSignIn(provider.providerId, scopes);
}

signInWithTwitter() {
  const provider = new auth.TwitterAuthProvider();
  return this.socialSignIn(provider.providerId);
}

socialSignIn(providerName: string, scopes?: Array<string>): Promise<any> {
  const provider = new auth.OAuthProvider(providerName);

  // add any permission scope you need
  if (scopes) {
    scopes.forEach(scope => {
      provider.addScope(scope);
    });
  }

  if (this.platform.is('desktop')) {
    return this.angularFire.signInWithPopup(provider);
  } else {
    // web but not desktop, for example mobile PWA
    return this.angularFire.signInWithRedirect(provider);
  }
}

Then, in the SignInPage (located in src/app/sign-in/sign-in.page.ts) we will inject our FirebaseAuthService. Now, when the user clicks the "Sign In with Facebook" button from the UI, we will invoke the following method:

facebookSignIn() {
  this.authService.signInWithFacebook()
  .then((result: any) => {
    if (result.additionalUserInfo) {
      // to get all the sign in provider's information
      this.authService.setProviderAdditionalInfo(result.additionalUserInfo.profile);
    }
    // This gives you a Facebook Access Token. You can use it to access the Facebook API.
    // const token = result.credential.accessToken;
    // The signed-in user info is in result.user;
    this.redirectLoggedUserToProfilePage();
  }).catch((error) => {
    // Handle Errors here.
    console.log(error);
  });
}

// Once the auth provider finished the authentication flow, and the auth redirect completes,
// redirect the user to the profile page
redirectLoggedUserToProfilePage() {
  // As we are calling the Angular router navigation inside a subscribe method, the navigation will be triggered outside Angular zone.
  // That's why we need to wrap the router navigation call inside an ngZone wrapper
  this.ngZone.run(() => {
    this.router.navigate(['profile']);
  });
}

Once the user is authenticated with any of the providers, he will be redirected to the profile page.

You can see the complete code for the other sign in providers by downloading the Ionic Firebase demo app provided in this tutorial.

After a user signs in our application through one of these social providers, we will see their information from 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 need to create some basic sign in and sign up forms.

In our SignInPage and SignUpPage, we will create simple sign in and sign up forms with email and password inputs. Then, we add signUpWithEmail() and signInWithEmail() methods which use the data the user entered in the form and tries to perform the authentication operation in Firebase.

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

signUpWithEmail() {
  this.authService.signUpWithEmail(this.signUpForm.value['email'], this.signUpForm.value['password'])
  .then(user => {
    // navigate to user profile
    this.redirectLoggedUserToProfilePage();
  })
  .catch(error => {
    this.submitError = error.message;
  });
}

The sign in method is similar, so I will not repeat the implementation here. You can see the code in the src/app/sign-in/sign-in.page.ts

In this Ionic 5 Firebase Authentication tutorial we explained how to add the most common sign in methods, both social (Facebook, Twitter, Google) and using email/password using AngularFire.

To help you, we built an example Ionic Framework application that allows users to log in and log out using all the previously mentioned authentication options. Once they log in, they will see a profile page with their basic profile info taken from the authentication provider. Download this app for free and add Firebase authentication to your Ionic Angular app!

We also explained the extra configurations needed when enabling native sign using Capacitor Firebase Auth.

We created Ionic 6 Full Starter App — PRO version to help developers like you save development and design time. In this Ionic Firebase app you will find Firebase Authentication with both web and mobile implementations.

This Ionic Firebase Starter App also includes an advanced Firebase CRUD integration.

Ionic 5 Firebase Authentication
Ionic 5 Firebase Authentication
Ionic 5 Firebase Authentication

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

I hope this Ionic Firebase tutorial was helpful. If you have any questions or feedback don't hesitate to leave a comment on the comments section below.

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