Using Firebase User Authentication in Ionic2

Image

Here’s how I was able to add Firebase User Authentication to the ionic-conference-app

Install the ionic-conference-app and test it locally to make sure it runs correctly

To install the ionic-conference-app follow the steps below (taken verbatim from the Getting Started section of the Github project page)

  1. Clone repository
  2. Run npm install from the project root
  3. Install the ionic CLI (npm install -g [email protected])
  4. Run ionic serve in a terminal from the project root

Open index.html and add the Firebase library script tag

    <!DOCTYPE html>
    <html dir="ltr" lang="en">
    <head>
      <meta charset="UTF-8">
      <title>Ionic Conference</title>
      <!--<meta http-equiv="Content-Security-Policy" content="script-src 'self' https://maps.gstatic.com/ https://*.googleapis.com/ http://localhost:* 'unsafe-inline' 'unsafe-eval'">-->
      <meta http-equiv="Content-Security-Policy" content="script-src * 'unsafe-inline' 'unsafe-eval'">
      <meta name="format-detection" content="telephone=no">
      <meta name="msapplication-tap-highlight" content="no">
      <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">

      <!-- Add Firebase Library Here -->
      <script src="https://cdn.firebase.com/js/client/2.4.0/firebase.js"></script>

      <!-- ionic dynamically decides which stylesheet to load -->
      <link ios-href="build/css/app.ios.css" rel="stylesheet">
      <link md-href="build/css/app.md.css" rel="stylesheet">
    </head>
    <body>

      <!-- <ion-app> is where the app's HTML loads -->
      <ion-app>/ion-app>

      <!-- cordova.js required for cordova apps -->
      <script src="cordova.js"></script>

      <!-- the bundle which is built from the app's source code -->
      <script src="build/js/app.bundle.js"></script>

      <!-- google maps script is loaded last as to not block rendering -->
      <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBvhp5ELJ3lgUdwq7PQIcZssUiWID8vzQ4"></script>
    </body>
    </html>

Open the login.js file

We need to capture the username and password from the login screen and send them to Firebase for authentication. It is very important to observe the following 3 snippets of code:

  1. The Firebase URL (this.firebaseurl) and the authorization handler (this.authHandler) are added to the constructor of the class
  2. The onLogin(form) method contains the actual user authentication logic. Here a Firebase reference is created and the credentials attached before the request is sent to authenticate
  3. And finally, the authHandler(error, authData) is a callback function that is triggered on error or success events
    import {IonicApp, Page, NavController} from 'ionic/ionic';
    import {TabsPage} from '../tabs/tabs';
    import {SignupPage} from '../signup/signup';
    import {UserData} from '../../providers/user-data';


    @Page({
      templateUrl: 'build/pages/login/login.html'
    })
    export class LoginPage {
      constructor(nav: NavController, userData: UserData) {
        this.nav = nav;
        this.userData = userData;

        this.login = {};
        this.submitted = false;
        
        this.firebaseUrl = "https://brilliant-inferno-1044.firebaseio.com";
        this.authHandler();
      }

      onLogin(form) {
        this.submitted = true;

        if (form.valid) {
          this.userData.login();
          
          /* Authenticate User */ 
          var ref = new Firebase(this.firebaseUrl);
          ref.authWithPassword({
            email    : form.controls.username.value,
            password : form.controls.password.value
          }, this.authHandler);
          
        }
      }
      
      authHandler(error, authData) {
        if (error) {
            console.log("Login Failed!", error);
        } else {
            this.nav.push(TabsPage);
        }
      }
      
      onSignup() {
        this.nav.push(SignupPage);
      }
    }

Now let’s open the user-data.js file

We need to add two local variables to the constructor in the user-data.js file to hold the username and password

    constructor(events: Events) {
      this._favorites = [];
      this.storage = new Storage(LocalStorage);
      this.events = events;
      this.HAS_LOGGED_IN = 'hasLoggedIn';
      this.username = '';
      this.password = '';
    }

That’s it!!!

We have Firebase authentication fully configured with our ionic-conference-app

Please note

At the time of this post I’m using the following configuration:

  1. Cordova CLI: 5.4.1
  2. Gulp version: CLI version 3.8.11
  3. Gulp local: Local version 3.9.0
  4. Ionic Version: 2.0.0-alpha.56
  5. Ionic CLI Version: 2.0.0-beta.17
  6. Ionic App Lib Version: 2.0.0-beta.8
  7. OS: Windows 7
  8. Node Version: v5.1.1

Social Login with Firebase

If you’re looking for OAuth Social Login with Firebase, check out this amazing article: Ionic 2 | Successful OAuth Social Login with Firebase

Disclaimer

This approach may not comply to Best Practices or there may be better ways to add Firebase to an ionic 2 app. If you know, please share!

Me

Luis Cabrera is a family man and a dedicated dad. He lives in Florida, where he works as an Applications Architect for one of the most recognizable brands in the US. In his spare time, Luis likes to develop apps using ionic and Firebase. Aside from technology and family, he enjoys the outdoors and working on his horse farm.

Older posts...

Written by

Get in touch!

Notice any mistakes?
Leave me a message