Ionic 5 Angular Firebase Authentication Example Tutorial

In this tutorial, we will learn how to add Firebase authentication in the Ionic 5 angular application using Firebase and Angular Fire npm packages.

We will explain to you how to create a Firebase project and how to register a user using email id and password, also how to log in with email and password not just that we will also explain how to integrate Firebase logout feature in ionic angular app.

Firebase is a handy cloud-based backend as a service; it offers immaculate documentation for building swift web and mobile applications. It comes with Firestore and Realtime database services, simple authentication, social authentication, top-notch storage, handy functions, and an impeccable dashboard for monitoring data and analytics.

You can create various types of authentication with Firebase Sign-in providers, and This Ionic Firebase authentication guide will focus on Email/Password, Google and Facebook; however, you may create login with Phone, Play Games, Game Center, Twitter, GitHub, Yahoo, Microsoft, Apple and Anonymus.

You just have to visit the Firebase authentication section and enable the auth provider to build an auth service.

Ionic 5 Angular Firebase Authentication Example

  • Step 1: Create Ionic App
  • Step 2: Set Up Routes
  • Step 3: Create Firebase Project
  • Step 4: Install Firebase and AngularFire Packages
  • Step 5: Register Firebase Modules in AppModule
  • Step 6: Create Service
  • Step 7: Implement Firebase User Registration
  • Step 8: Firebase SignIn with Email and Password
  • Step 9: Firebase Logout
  • Step 10: Run Ionic App

Create Ionic App

Ionic development begins by installing Ionic CLI, command to install the Ionic command-line interface tool.

npm install -g @ionic/cli

Ionic CLI command allows you to install the ionic, angular application.

ionic start ionic-firebase-auth blank --type=angular

Get into the app folder:

cd ionic-firebase-auth

Execute the recommended commands to create new pages to handle auth in the ionic app.

ionic generate page login

ionic generate page register

ionic generate page dashboard

Don’t forget to delete the Home page component because we are not using this component.

Set Up Routes

In this step, we will set up the routes. Open app-routing.module.ts file, and replace the current code with the following code.

import { NgModule } from '@angular/core';
import { PreloadAllModules, RouterModule, Routes } from '@angular/router';

const routes: Routes = [
  {
    path: '',
    redirectTo: 'register',
    pathMatch: 'full'
  },
  {
    path: 'login',
    loadChildren: () => import('./login/login.module').then( m => m.LoginPageModule)
  },
  {
    path: 'register',
    loadChildren: () => import('./register/register.module').then( m => m.RegisterPageModule)
  },
  {
    path: 'dashboard',
    loadChildren: () => import('./dashboard/dashboard.module').then( m => m.DashboardPageModule)
  },
];

@NgModule({
  imports: [
    RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })
  ],
  exports: [RouterModule]
})

export class AppRoutingModule { }

Create Firebase Project

You need to go to firebase.google.com website, then sign in with your email.

Further, create a new firebase project.

Firebase Create Account

Enter firebase project name.

Create a project

Then, add Firebase to your app.

add Firebase to app

Next, add a project name and include Firebase to your web app.

add firebase

Next, copy Firebase configuration keys, we need these keys later to connect ionic to firebase.

Firebase configuration keys

Thereafter, head over to Authentication section then open the Sign-in method tab, in here you can see multiple auth methods. Hence, we have to enable every method that we are going to implement.

For instance, we have turned on the Email/Password method for this tutorial.

Firebase Authentication

Install Firebase and AngularFire Packages

Next, add the firebase and angular fire packages using the npm command, hence type the suggested command on the command prompt and then execute the command to install the packages.

npm i firebase @angular/fire

We have created the Firebase project, and we have to make the connection between ionic and firebase.

Therefore, open the environments/environment.ts file and add the Firebase configurations.

export const environment = {
  production: false,
  firebaseConfig: {
    apiKey: "AIzaSyDOCAbC123dEf456GhI789jKl01-MnO",
    authDomain: "myapp-project-123.firebaseapp.com",
    databaseURL: "https://myapp-project-123.firebaseio.com",
    projectId: "myapp-project-123",
    storageBucket: "myapp-project-123.appspot.com",
    messagingSenderId: "65211879809",
    appId: "1:65211879909:web:3ae38ef1cdcb2e01fe5f0c",
    measurementId: "G-8GSGZQ44ST"
  }
};

Register Firebase Modules in AppModule

Open app.module.ts file and import AngularFireModule, AngularFireAuthModule, and environment similarly register them in the imports array to invoke the Firebase and Ionic connection.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';
import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';

// Firebase
import { AngularFireModule } from '@angular/fire';
import { AngularFireAuthModule } from '@angular/fire/auth';
import { environment } from '../environments/environment';

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [
    BrowserModule, 
    IonicModule.forRoot(), 
    AppRoutingModule,
    AngularFireModule.initializeApp(environment.firebaseConfig),
    AngularFireAuthModule
  ],
  providers: [
    { 
      provide: RouteReuseStrategy, 
      useClass: IonicRouteStrategy 
    }
  ],
  bootstrap: [AppComponent],
})

export class AppModule {}

Create Service

Let us create the ionic, angular service and conjugate the entire code in this file for making reusable functions and method for handling ionic firebase auth service immaculately.

Run command to generate angular service in ionic app.

ng g s ionicAuth

Open and then add the following code in the ionic-auth.service.ts file.

import { Injectable } from '@angular/core';
import { AngularFireAuth } from '@angular/fire/auth';

@Injectable({
  providedIn: 'root'
})

export class IonicAuthService {

  constructor(
    private angularFireAuth: AngularFireAuth
  ) { }  

  createUser(value) {
    return new Promise<any>((resolve, reject) => {
      this.angularFireAuth.createUserWithEmailAndPassword(value.email, value.password)
        .then(
          res => resolve(res),
          err => reject(err))
    })
  }

  signinUser(value) {
    return new Promise<any>((resolve, reject) => {
      this.angularFireAuth.signInWithEmailAndPassword(value.email, value.password)
        .then(
          res => resolve(res),
          err => reject(err))
    })
  }

  signoutUser() {
    return new Promise<void>((resolve, reject) => {
      if (this.angularFireAuth.currentUser) {
        this.angularFireAuth.signOut()
          .then(() => {
            console.log("Sign out");
            resolve();
          }).catch(() => {
            reject();
          });
      }
    })
  }

  userDetails() {
    return this.angularFireAuth.user
  }

}

Implement Firebase User Registration in Ionic

To integrate the firebase user registration feature in ionic, we need to get user values through the form. Accordingly, we are using reactive forms api; make sure to register ReactiveFormsModule in the register.module.ts file.

import { FormsModule, ReactiveFormsModule } from '@angular/forms';

@NgModule({
  imports: [
    FormsModule,
    ReactiveFormsModule,
  ]
})

There are two things we are doing with this code snippet. First, creating the form group to get the user-provided values and accessing the createUser() method, passing the user details, and setting up a function to navigate to the login page.

Open and update register.page.ts file.

import { Component, OnInit } from '@angular/core';
import { Router } from "@angular/router";
import { IonicAuthService } from '../ionic-auth.service';
import { FormGroup, FormBuilder, Validators, FormControl } from '@angular/forms';

@Component({
  selector: 'app-register',
  templateUrl: './register.page.html',
  styleUrls: ['./register.page.scss'],
})

export class RegisterPage implements OnInit {

  userForm: FormGroup;
  successMsg: string = '';
  errorMsg: string = '';
  

  error_msg = {
    'email': [
      { 
        type: 'required', 
        message: 'Provide email.' 
      },
      { 
        type: 'pattern', 
        message: 'Email is not valid.' 
      }
    ],
    'password': [
      { 
        type: 'required', 
        message: 'Password is required.' 
      },
      { 
        type: 'minlength', 
        message: 'Password length should be 6 characters long.' 
      }
    ]
  };

  constructor(
    private router: Router,
    private ionicAuthService: IonicAuthService,
    private fb: FormBuilder
  ) { }

  ngOnInit() {
    this.userForm = this.fb.group({
      email: new FormControl('', Validators.compose([
        Validators.required,
        Validators.pattern('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$')
      ])),
      password: new FormControl('', Validators.compose([
        Validators.minLength(6),
        Validators.required
      ])),
    });
  }

  signUp(value) {
    this.ionicAuthService.createUser(value)
      .then((response) => {
        this.errorMsg = "";
        this.successMsg = "New user created.";
      }, error => {
        this.errorMsg = error.message;
        this.successMsg = "";
      })
  }

  goToLogin() {
    this.router.navigateByUrl('login');
  }

}

Next, head over to the register HTML template, create the basic form and define the formGroup likewise use the ng-container to show the errors for the user registration page.

Open and update register.page.html file.

<ion-header>
  <ion-toolbar color="danger">
    <ion-title>User Registeration</ion-title>
  </ion-toolbar>
</ion-header>

<ion-content class="ion-padding">
  <form class="form" [formGroup]="userForm" (ngSubmit)="signUp(userForm.value)">
    <ion-item>
      <ion-label position="floating">Email</ion-label>
      <ion-input type="text" formControlName="email"></ion-input>
    </ion-item>
    
    <ng-container *ngFor="let error of error_msg.email">
      <div *ngIf="userForm.get('email').hasError(error.type) && (userForm.get('email').dirty || userForm.get('email').touched)">
        {{ error.message }}
      </div>
    </ng-container>

    <ion-item>
      <ion-label position="floating" color="primary">Password</ion-label>
      <ion-input type="password" formControlName="password" class="form-controll" required></ion-input>
    </ion-item>
    
    <ng-container *ngFor="let error of error_msg.password">
        <div *ngIf="userForm.get('password').hasError(error.type) && (userForm.get('password').dirty || userForm.get('password').touched)">
          {{ error.message }}
        </div>
    </ng-container>

    <ion-button type="submit" expand="block" [disabled]="!userForm.valid">Register</ion-button>
    
    <label class="ion-text-center" color="danger">{{errorMsg}}</label>
    <label class="ion-text-center" color="success">{{successMsg}}</label>
  </form>
  <p class="ion-text-center">Already registered? <a (click)="goToLogin()">Login</a></p>
</ion-content>

Ionic Firebase User Registration

Firebase SignIn with Email and Password

Similarly, we also have to create the form in the login template hence, import ReactiveFormsModule in the login.module.ts file.

import { FormsModule, ReactiveFormsModule } from '@angular/forms';

@NgModule({
  imports: [
    FormsModule,
    ReactiveFormsModule,
  ]
})

In this step, we will import IonicAuthService, access the signinUser() method, and log in with the registered user’s email and password. If successfully logged in, then redirect to the dashboard page.

Open and update login.page.ts file.

import { Component, OnInit } from '@angular/core';
import { Router } from "@angular/router";
import { IonicAuthService } from '../ionic-auth.service';
import { FormGroup, FormBuilder, Validators, FormControl } from '@angular/forms';

@Component({
  selector: 'app-login',
  templateUrl: './login.page.html',
  styleUrls: ['./login.page.scss'],
})

export class LoginPage implements OnInit {

  userForm: FormGroup;
  successMsg: string = '';
  errorMsg: string = '';
  

  error_msg = {
    'email': [
      { 
        type: 'required', 
        message: 'Provide email.' 
      },
      { 
        type: 'pattern', 
        message: 'Email is not valid.' 
      }
    ],
    'password': [
      { 
        type: 'required', 
        message: 'Password is required.' 
      },
      { 
        type: 'minlength', 
        message: 'Password length should be 6 characters long.' 
      }
    ]
  };

  constructor(
    private router: Router,
    private ionicAuthService: IonicAuthService,
    private fb: FormBuilder
  ) { }

  ngOnInit() {
    this.userForm = this.fb.group({
      email: new FormControl('', Validators.compose([
        Validators.required,
        Validators.pattern('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$')
      ])),
      password: new FormControl('', Validators.compose([
        Validators.minLength(6),
        Validators.required
      ])),
    });
  }

  signIn(value) {
    this.ionicAuthService.signinUser(value)
      .then((response) => {
        console.log(response)
        this.errorMsg = "";
        this.router.navigateByUrl('dashboard');
      }, error => {
        this.errorMsg = error.message;
        this.successMsg = "";
      })
  }

  goToSignup() {
    this.router.navigateByUrl('register');
  }

}

Open and add login.page.html file.

<ion-header>
  <ion-toolbar color="success">
    <ion-title>Login</ion-title>
  </ion-toolbar>
</ion-header>

<ion-content class="ion-padding">
  <form class="form" [formGroup]="userForm" (ngSubmit)="signIn(userForm.value)">
    <ion-item>
      <ion-label position="floating">Email</ion-label>
      <ion-input type="text" formControlName="email"></ion-input>
    </ion-item>
    
    <ng-container *ngFor="let error of error_msg.email">
      <div *ngIf="userForm.get('email').hasError(error.type) && (userForm.get('email').dirty || userForm.get('email').touched)">
        {{ error.message }}
      </div>
    </ng-container>

    <ion-item>
      <ion-label position="floating" color="primary">Password</ion-label>
      <ion-input type="password" formControlName="password" class="form-controll" required></ion-input>
    </ion-item>
    
    <ng-container *ngFor="let error of error_msg.password">
        <div *ngIf="userForm.get('password').hasError(error.type) && (userForm.get('password').dirty || userForm.get('password').touched)">
          {{ error.message }}
        </div>
    </ng-container>

    <ion-button type="submit" expand="block" [disabled]="!userForm.valid">Signin</ion-button>
    
    <label class="ion-text-center" color="danger">{{errorMsg}}</label>
  </form>
  <p class="ion-text-center">Not registered yet? <a (click)="goToSignup()">Register</a></p>
</ion-content>

Ionic Firebase Login with Email and Password

Firebase User Details and Logout

This last segment will show you how to create firebase logout functionality and fetch the logged-in user details and display them in the ionic view.

Open and update dashboard.page.ts file.

import { Component, OnInit } from '@angular/core';
import { Router } from "@angular/router";
import { IonicAuthService } from '../ionic-auth.service';

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.page.html',
  styleUrls: ['./dashboard.page.scss'],
})

export class DashboardPage implements OnInit {
  userDetail: string;

  constructor(
    private router: Router,
    private ionicAuthService: IonicAuthService
  ) { }

  ngOnInit() {
    this.ionicAuthService.userDetails().subscribe(response => {
      if (response !== null) {
        this.userDetail = response.email;
      } else {
        this.router.navigateByUrl('');
      }
    }, error => {
      console.log(error);
    })
  }

  signOut() {
    this.ionicAuthService.signoutUser()
      .then(res => {
        this.router.navigateByUrl('login');
      })
      .catch(error => {
        console.log(error);
      })
  }
}

Open and update dashboard.page.html file.

<ion-header>
  <ion-toolbar>
    <ion-title>App Dashboard</ion-title>
  </ion-toolbar>
</ion-header>

<ion-content class="ion-padding">
  <ion-grid>
    <ion-row>
      <ion-col text-center>
        Welcome User!

        <p>User email : <strong>{{ userDetail }}</strong></p>
      </ion-col>
    </ion-row>

    <ion-button type="submit" color="danger" expand="block" (click)="signOut()">Signout</ion-button>
  </ion-grid>
</ion-content>

Firebase User Details and Logout

Run Ionic App

We are left with adding a platform, creating the build and starting the app on the real or virtual device in the last step. So make sure to follow the below instructions.

# iOS
ionic cordova platform add ios

# Android
ionic cordova platform add android


# iOS
ionic cordova build ios

# Android
ionic cordova build android


# iOS
ionic cordova run ios -l

# Android
ionic cordova run android -l

Conclusion

Ionic 5 Firebase authentication tutorial is ended; throughout this extensive guide, we discussed implementing Firebase Authentication in Ionic, angular app. We step by step went through every step to create Firebase user registration, create firebase login with email and password, and created firebase social login with Facebook and Google in the Ionic app.