FIREBASE AUTHENTICATION USING IONIC 4 | IONIC 4 FIREBASE TUTORIAL

Share the post

Hello All, In the last Ionic 4 tutorial we had discussed How to implement Calendar in Ionic 4. Now, In this Ionic 4 tutorial, We will discuss How to implement Firebase authentication using Ionic 4? We will discuss this topic with the help of an example. We will consider one Sign Up page in our app for user registration. After that, We will give one Login Page to login with entered credentials. In simple words, the User will register first then Authenticate & login with Firebase API.

We are going to use the Ionic 4 framework to implement this functionality in our application. If you enter the following command on CLI (Command Line Interface) then you will get all installed software versions.

ionic info

Version Using for this Project

    Ionic:

    Ionic CLI: 5.4.16
    Ionic Framework               : @ionic/angular 5.0.7
    @angular-devkit/build-angular : 0.803.26
    @angular-devkit/schematics    : 8.3.26
    @angular/cli                  : 8.3.26
    @ionic/angular-toolkit        : 2.2.0


    Cordova:

    Cordova CLI: not installed
    Cordova Platforms: android 8.1.0
    Cordova Plugins   : cordova-plugin-ionic-keyboard 2.2.0, cordova-plugin-ionic-webview 4.2.1, (and 9 other plugins)
 
    Utility:

    cordova-res : not installed
    native-run  : 1.3.0

   System:

    Android SDK Tools : 26.1.1
    NodeJS            : v10.15.3
    npm               : 6.4.1
    OS                : Windows 10

After installing the necessary dependencies we will move ahead to create a new project in Firebase.

How to create a new project in Firebase?

Follow the below steps to create a new project in Firebase

Step1: Go to Firebase console

Step 2: Click on Create a project

Create Firebase Project
Create Firebase Project

Step 3 : Enter Project Name

Write Firebase Project Name
Write Firebase Project Name

Step 4 : Enable google analytics

Enable Google Analytics
Enable Google Analytics

Step 5: Select Google analytics account

Select Google Analytics Account
Select Google Analytics Account

Finally, Click on Create project button. This is how we can able to a new project in Firebase.

Now, We will move ahead to enable the setting for Email Authentication, Database Creation & Setup .\

Please see the below steps to enable Email Authentication.

How to Enable Email Authentication in Firebase

Step 1 : Enable Sign- In method

Go to Authentication -> Sign-in method

Enable Sign-in Method
Enable Sign-in Method

Step 2: Click on Email/Password

Click On Email/Password option
Click On Email/Password option

Step 3: Enable check box & click save

Enable Check box
Enable Check box

Step 4: See the Email/Password option enabled

Email/Password Changed to Enabled
Email/Password Changed to Enabled

Now, We will go ahead to Create Real-time Database & do the setup of the Database

Steps to Create Realtime Database in Firebase

Step 1 : Click on Realtime Database & Create Database

Crate a Firebase Realtime Database
Crate a Firebase Realtime Database

Step 2 : Select Realtime Database location

Setup Database
Setup Database

Step 3 : Security Rules

Security Rules
Security Rules

Firebase setup is done. Now, We will go ahead to create an Ionic 4 application to implement Firebase authentication.

Steps to implement Firebase authentication using Ionic 4

Step1: Create a new project

ionic start IONICHELPER blank --type=angular

Step 2: Create a new page

ionic g page firebase-login

Step 3 : Install dependencies

npm install firebase --save

Step 4: Change in app.component.ts

We have to initialize the Firebase configuration in app.component.ts.

import firebase module

import * as firebase from 'firebase';

Create constant for configuration parameter

const configuration = {
  apiKey: "YOUR API KEY,
  authDomain: "YOUR AUTH DOMAIN",
  databaseURL: "YOUR DATABASE URL",
  projectId: "YOUR PROJECT ID",
  storageBucket: "YOUR STORAGE BUCKET",
  messagingSenderId: "YOUR SENDER ID",
  appId: "YOUR APP ID",
  measurementId: "YOUR MEASEUREMENT ID"
}

Now If you want to get the above firebase configuration parameter to follow below easy steps

How to get Firebase Configuration Parameters

Step 4.1 : Click to add app

Add Web Application
Add Web Application

Step 4.2 : Click on web app icon

Click On Web Icon
Click On Web Icon

Step 4.3 : Register app

Register app
Register app

Step 4.4 : Get the configuration parameter here

Get Firebase configuration parameters
Get Firebase configuration parameters

This is how you can get the Firebase configuration parameter. Paste this parameter in your app.component.ts as mentioned in Step 4. After this create one more method to initialize firebase.

 initFirebase() {
    firebase.default.initializeApp(configuration);
  }

Now, your completer app.component.ts will look like this

import { Component } from '@angular/core';

import { Platform } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';
import * as firebase from 'firebase';

const configuration = {
  apiKey: "",
  authDomain: "",
  databaseURL: "",
  projectId: "",
  storageBucket: "",
  messagingSenderId: "",
  appId: "",
  measurementId: ""
}

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.scss']
})
export class AppComponent {

  constructor(
    private platform: Platform,
    private splashScreen: SplashScreen,
    private statusBar: StatusBar
  ) {
    this.initializeApp();
    this.initFirebase();
  }

  initializeApp() {
    this.platform.ready().then(() => {
      this.statusBar.styleDefault();
      this.splashScreen.hide();

    });
  }

  initFirebase() {
    firebase.default.initializeApp(configuration);
  }
}

Step 5: HTML

Now, We will create two separate div on the single HTML page. One for Sign Up Form & Other for the Login form. Please copy the below HTML to your firebase-login.page.html

<ion-header>
  <ion-toolbar>
    <ion-title>Firebase Login Example</ion-title>
  </ion-toolbar>
</ion-header>

<ion-content>

  <div *ngIf="showLoginPage">

    <h1>Login Form</h1>

    <ion-item>
      <ion-label>Email Id</ion-label>
      <ion-input type="email" [(ngModel)]="emailId"></ion-input>
    </ion-item>

    <ion-item>
      <ion-label>Password</ion-label>
      <ion-input type="password" [(ngModel)]="password"></ion-input>
    </ion-item>

    <ion-item>
      <ion-button (click)="doLogin()">Login</ion-button>
      <ion-button (click)="showSignUp()">New User? Do SignUp</ion-button>

    </ion-item>
  </div>


  <div *ngIf="showSignUpPage">

    <h1>SignUp Form</h1>

    <ion-item>
      <ion-label>Email Id</ion-label>
      <ion-input type="email" [(ngModel)]="emailId"></ion-input>
    </ion-item>

    <ion-item>
      <ion-label>Password</ion-label>
      <ion-input type="password" [(ngModel)]="password"></ion-input>
    </ion-item>

    <ion-item>
      <ion-button (click)="doSignUp()">SignUp</ion-button>
      <ion-button (click)="showLogin()">Already Register? Do Login</ion-button>
    </ion-item>
  </div>


</ion-content>

Step 6 : TS

Copy below code in your firebase-login.page.ts

import { Component, OnInit } from '@angular/core';
import * as firebase from 'firebase';

@Component({
  selector: 'app-firebase-login',
  templateUrl: './firebase-login.page.html',
  styleUrls: ['./firebase-login.page.scss'],
})
export class FirebaseLoginPage implements OnInit {
  emailId: any;
  password: any;
  showLoginPage: boolean = false;
  showSignUpPage: boolean = true;

  constructor() { }

  ngOnInit() {
  }

  doLogin() {
    firebase.default.auth().signInWithEmailAndPassword(this.emailId, this.password).then(result => {
      console.log(result);
      alert("Login successfully");
    }).catch(error => {
      console.log(error);
      alert("Error occured. Please try again");
    });
  }

  doSignUp() {
    firebase.default.auth().createUserWithEmailAndPassword(this.emailId, this.password).then(result => {
      console.log(result);
      alert("Register successfully");
    }).catch(error => {
      console.log(error);
      alert("Error occured. Please try again");
    });
  }

  showLogin() {
    this.showLoginPage = true;
    this.showSignUpPage = false;
  }

  showSignUp() {
    this.showLoginPage = false;
    this.showSignUpPage = true;
  }
}

Here, With the click of the SignUp button, We are calling the internal function doSignUp(). In this function we are calling the firebase method createUserWithEmailAndPassword(this.emailId, this.password), In this method, We are passing email Id & password two parameters. This method will register the particular email & password in the Firebase database.

After registering successfully user can move on to Login Page to do login. Now, With the click of the Login button, We are calling the internal function doLogin(). In this function, We are calling the firebase method signInWithEmailAndPassword(this.emailId, this.password). After this, The user will get Authenticate by the Firebase server & Which will allow them to login into our app.

Step 7: Output

Sign up Output
Sign up Output

After registering successfully user will appear on user list. You can see this list on Authentication -> Users

Users List
Users List
Login Output
Login Output

Output

2 thoughts on “FIREBASE AUTHENTICATION USING IONIC 4 | IONIC 4 FIREBASE TUTORIAL”

Leave a Comment