Firebase authentication in Angular2 application with Angularfire2

Implementing authentication in web apps is a tedious and repetitive task. What’s more, it’s very easy to do it wrong and expose security holes in our app. Fortunately, Firebase Authentication comes to rescue offering authentication as a service. It means that you no longer need to implement storage and verification of credentials, email verification, password recovery, etc. In this post I’ll explain how to add email/password authentication to an Angular2 application.

Site note: Firebase Authentication can be very useful when building a serverless application.

For reference, here is a working example illustrating this article: https://github.com/miloszpp/angularfire-sdk-auth-sample.

 

Overview

Firebase offers two ways of implementing authentication:

  • FirebaseUI Auth – a library of ready-to-use GUI components (such as login/registration forms, password recovery, etc.)
  • Firebase Authentication SDK – a more flexible approach in which we need to implement above components ourselves; the role of Firebase is to store and verify user credentials; let’s focus on this one

We’ll implement three components:

  • Register component will show a registration form and will ask Firebase to create an entry for a user upon submission
  • Login component will show a login form and will ask Firebase to verify provided credentials upon submission
  • Home component will show the currently logged user (provided there is one)

We’ll use the excellent Angularfire2 library. It provides an Angular-friendly abstraction layer over Firebase. Additionally, it exposes authentication state as an observable, making it very easy for other components to subscribe to events such as login and logout.

Preparations

To begin with, let’s install Angularfire2 and Firebase modules:

Next, we need to enable email/password authentication method in the Firebase console.

Firebase: enabling email/password authentication

Finally, let’s load Angularfire2 in our app.module.ts:

Login component

Firstly, let’s inject AngularFire into the component:

As you can see, this.af.auth  is an observable. It fires whenever an event related to authentication occurs. In our case, it’s either logging in or logging out. FirebaseAuthState  stores information about currently logged user.

Next, let’s add two methods for logging in and logging out:

As you can see, we simply propagate calls to the Angularfire2 API. When logging in, we need to provide email and password (encapsulated in model).

Finally, we need some HTML to display the form:

The form is only visible when the user is not logged in ( authState  will be undefined). Otherwise, we show the user name and the logout button.

Register component

We’ve allowed our users to logged in but so far there are no registered users! Let’s fix that and create a registration component.

Firstly, we need to inject the AngularFire service just like we did in the login controller.

Next, let’s create a method to be called when the user provides his registration details:

Finally, here goes the HTML form:

Summary

In this tutorial I showed you how to take advantage of Firebase Authentication and use it in an Angular 2 application. This example doesn’t exploit the full potential of Firebase Authentication – it can also do email verification (with actual email sending and customizable email templates), password recovery and logging in with social accounts (Facebook, Twitter, etc.). I will touch on these topics in the following articles.

Let me know if you have any feedback regarding this post – feel free to post a comment!

10 thoughts on “Firebase authentication in Angular2 application with Angularfire2

    1. Hi! Unfortunately, Angularfire2 doesn’t support getting/saving user profile data at the moment. You’d need to use the native firebase module for that.


      var firebase = require("firebase");
      var user = firebase.auth().currentUser;

      user.updateProfile({
      displayName: "Jane Q. User",
      photoURL: "https://example.com/jane-q-user/profile.jpg"
      })

      Check out https://firebase.google.com/docs/auth/web/manage-users for more examples.

  1. Hi milosz, great post. Can you please advise if you have a tutorial for email verification (with actual email sending and customizable email templates), password recovery? or how this can be done? I’ve looked all over

    1. Hi Johnny, glad to hear that. As far as I understand you can’t do this with Angularfire2 at the moment. As explained in this discussion, they don’t plan to expose all of the features of Firebase Authentication through their API: https://github.com/angular/angularfire2/issues/55#issuecomment-263368090. Instead, they advise using the underlying Firebase API.

      You can have a look at the docs and try to figure it out yourself: https://firebase.google.com/docs/reference/js/firebase.User#sendEmailVerification.

      Let me know if you run into any issues, I’ll be happy to help.

      1. thanks, i can send an email when logging in using this.af.auth.getAuth().auth.sendEmailVerification()

        but i think my logic is wrong somewhere, so i get a verification email and automatically logs me in. unless you are right and its not supported.

  2. i used this tutorial to setup the login and password. I only did email, not google and facebook.
    https://coursetro.com/posts/code/32/Create-a-Full-Angular-Authentication-System-with-Firebase

    then I used this.af.auth.getAuth().auth.sendEmailVerification()
    in the signup component.
    i used the sendEmailVerification like this, i get the verification email, but it doesn’t do much as i get logged in even without clicking on the link

    onSubmit(formData) {
    if(formData.valid) {
    console.log(formData.value);
    let user = this.af.auth.createUser({
    email: formData.value.email,
    password: formData.value.password
    }).then(
    (Success) => {
    this.af.auth.getAuth().auth.sendEmailVerification()
    this.router.navigate([‘/login’])
    }).catch(
    (err) => {
    this.error = err;
    })
    }
    }

    1. I think it’s the way it’s supposed to work.

      There is a boolean property User.emailVerified (https://firebase.google.com/docs/reference/js/firebase.User). When you call applyActionCode, all it does is set this property to true.

      So, anywhere you expect an authenticated user, instead of only checking whether a user is logged in you need to also check this property.

      You can access the property like this:
      af.auth.subscribe(authState => console.log(authState.auth.emailVerified))

Leave a Reply