Last update on Saturday, January 12th 2019

Using Firebase and AngularFire2 Basic Authentication in an Ionic application

Authentication sucks, we have to code on the client and on the server side, handle tokens, sessions, handle password resets, send the emails through an SMTP server and so much more.
Well ... not anymore, Firebase comes to the rescue!
The previous tutorial was just the tip of the iceberg, Firebase allows us to be lazy and have our authentication system done with 100 lines of code.

Firebase Setup

As usual we need to prepare Firebase first, it starts here.

ionic firebase angularfire login

And a new project:

ionic firebase angularfire create project

I'm just going to re-use the one from the previous tutorial on Firebase RealTime Database.

Then activating the service in the Authentication section:

ionic firebase angularfire add email password auth

That's it!

Linking the Firebase Account

Let's create our Ionic application, install Firebase and AngularFire:

ionic start ionic-firebase-auth blank
npm install firebase angularfire2 --save

AngularFire needs a configuration file to connect to Firebase, our file will be located in src/environments/environment.ts:

export const environment = {
  production: false,
  firebase: {
    apiKey: " AIzaSyAN4H-9VmncDG0PfqmuhmHrXuBtvCojT2E",
    authDomain: "todo-firebase-c4298.firebaseapp.com",
    projectId: "todo-firebase-c4298"
  }
};

This information is available in the Authentication section:

ionic firebase angularfire project information 2

We can now modify the app.module.ts file:

.
.
.
import { AngularFireAuthModule } from 'angularfire2/auth';
import { AngularFireModule } from 'angularfire2';
import { AngularFireAuth } from 'angularfire2/auth';

import { environment } from '../environments/environment';

@NgModule({
  .
  .
  .
  imports: [
    .
    .
    .
    AngularFireModule.initializeApp(environment.firebase),
    AngularFireAuthModule
  ],
  providers: [
    .
    .
    .,
    AngularFireAuth
  ]
})

The AngularFire Module is initialized here by using the configuration file that we previously created alongside the AngularFireAuth Module and the declaration of the AngularFireAuth Provider.

The Authentication

The home.html file will be very simple:

<ion-content padding>

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

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

  <div text-center>
    <button ion-button (click)="register(email, password)">Register</button>
    <button ion-button (click)="login(email, password)">Login</button>
  </div>

</ion-content>

Two properties: email and password.
The registration and login will be handled by two methods: register and login. Both of them require the email and password to act.

The home.ts is then built:

import { AngularFireAuth } from 'angularfire2/auth';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  constructor(public angularFireAuth: AngularFireAuth) {

  }
}

Nothing fancy here, we grab the AngularFireAuth Service and stock it in the angularFireAuth property.

Ok, so now we need the register and login methods, but also the sendEmailVerification so the user can legitimately activate its account, remember, you don't want to register users without verification, generally one account is linked to an email which could lead to identity thief.

The method is as follow:

  sendEmailVerification() {
    this.angularFireAuth.authState.subscribe(user => {
        user.sendEmailVerification()
        .then(() => {
          console.log('email sent');
        })
      });
  }

It does get tricky here.
The first thing that came to my mind was using an email address to directly send the email, however that's not how it works.
The user must be connected first in order to use the sendEmailVerification method.
We get this information by subscribing to the authState method in the angularFireAuth Service.
So if the user is already logged it's not logic no?
Nop, although the user is already logged in, there is a field that notifies us about the user status:

ionic firebase angularfire use email non verified

This one will only become true once the user clicks on the link in the email:

ionic firebase angularfire use email

Great so the security is now built.

We can move to the register method:

  register(email, password) {
    this.angularFireAuth.auth.createUserWithEmailAndPassword(email, password)
    .then((res) => {
      this.sendEmailVerification()
    })
    .catch((err)=> {
      //Do as you please here
    });
  }

Just like before using the angularFireAuth property, this time we use the auth property which contains most authentication related methods like createUserWithEmailAndPassword (that can't be more explicit), just use the email and password that we received from the form.
If everything is correct, we send the verification email. If not we can show the error to the user (ex: weak password, email already used, etc.).

The login method is simpler:

  login(username, password) {
    this.angularFireAuth.auth.signInWithEmailAndPassword(username, password)
      .then((user) => {
        if(user.emailVerified) {
          // Redirect the user here
        } else {
          // Tell the user to have a look at its mailbox
        }
      });
  }

This time we just use the signInWithEmailAndPassword method and receive the user information.
At this point, we can let the user in if the email is already verified or show a new button to use the email verification:

    <button ion-button (click)="sendEmailVerification()">
      Resend the email verification
    </button>

One last feature that you might need in case the user has lost its password ... using the sendPasswordResetEmail method:

  sendPassword(email) {
    this.angularFireAuth.auth.sendPasswordResetEmail(email)
    .then(() => {
      console.log('email sent');
    })
  }

And voila!

ionic firebase angularfire password reset

Conclusion

Four years ago creating an Authentication System was a one or two day task, now it only takes one or two hours thanks to services like Firebase (who knows maybe in 5 or 10 years it will take two minutes with voice command 😀).

All we need is setting up Firebase in the browser, importing AngularFire and AngularFireAuth Modules, then using the AngularFireAuth Service. On the other side, setting up OAuth with Ionic is a bit more complex, but that’s for another day.

If you liked this tutorial, you can learn more on Firebase’s database, storage, twitter authentication and cloud functions.

Adding Twitter Authentication with Firebase in Ionic

Learn how to mix
the Twitter OAut...
...

Using Firebase and AngularFire2 in an Ionic Real-Time TODO application

Learn how to use
Firebase RealTi...
...

Creating an Ionic PWA with Firebase Offline and Service Workers

Learn how to
create your first ...
...

Stay up to date


Join over 4000 other developers who already receive my tutorials and their source code out of the oven with other free JavaScript courses and an Angular cheatsheet!
Designed by Jaqsdesign