PRO Authentication Guards with AngularFire

First Published: 4 June 2019
Updated on: 4 June 2019

AngularFire dropped a new version (version 5.2.0) recently and added some great features.

One that immediately made me happy was the new AngularFireAuthGuard which is exactly what you’re thinking, its own Authentication Guard, meaning we don’t need to build our own anymore.

Today you’ll learn how to use AngularFire new built-in authentication guard, and how to tweak it to fit your needs.

We’ll cover the process in 4 straightforward steps:

  • Step #1: We’ll make sure @angular/fire is at least level 5.2.0.
  • Step #2: We’ll add AngularFireAuthGuard to our providers’ array.
  • Step #3: We’ll protect our routes with the AngularFireAuthGuard.
  • Step #4: We’ll learn how to tweak it to suit our needs.

That’s probably enough for an intro so let’s jump into coding :-)

Step #1: Make sure @angular/fire is at least 5.2.0

The first thing you need to do is to make sure you’re running on a version of AngularFire2 that supports this feature.

Go ahead and open your terminal, navigate to your project’s folder and type:

npm install firebase @angular/fire

Then check out your package.json file and make sure the version is at least 5.2.0 (That’s when they added the feature :-P).

Step #2: Add AngularFireAuthGuardto the providers array

Now it’s time to tell our app we’ll be using AngularFireAuthGuard, so go ahead and open your app.module.ts file and first import AngularFireAuthGuard and then add it to the providers’ array, it should look something like this:

import { AngularFireAuthGuard } from '@angular/fire/auth-guard';

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [
    ...
  ],
  providers: [
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy },
    AngularFireAuthGuard
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

Step #3: Protect your routes with the AngularFireAuthGuard

Protecting our routes is straightforward, all you need to do is to go into your app-routing.modulets and import AngularFireAuthGuard, then add it to the canActivate guard’s array for the routes you want to protect.

import { NgModule } from '@angular/core';
import { PreloadAllModules, RouterModule, Routes } from '@angular/router';
import { AngularFireAuthGuard } from '@angular/fire/auth-guard';

const routes: Routes = [
  { path: '', redirectTo: 'home', pathMatch: 'full' },
  {
    path: 'home',
    loadChildren: './home/home.module#HomePageModule',
    canActivate: [AngularFireAuthGuard]
  }
];

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

And with that our route is secure, it checks for authentication by default, so it won’t let unauthenticated users access your routes.

I know what you’re thinking, that’s not enough, how will your app know where to redirect unauthenticated users?

That’s when customization comes in handy! And that’s what we’ll see on the next step.

Step #4: We’ll learn how to tweak it to suit our needs

To customize the behavior of AngularFireAuthGuard, you can pass default (or your own!) RXJS pipes through the route data’s authGuardPipe key.

You’ll learn how to do that with the most common use case our apps have. Redirect users to a login or landing page when they haven’t logged in.

For that, the first thing you’ll do is to import the redirectUnauthorizedTo pipe and the AngularFireAuthGuard custom’s canActivate method:

import { redirectUnauthorizedTo, canActivate } from '@angular/fire/auth-guard';

After that, we want to create a variable that holds the pipe with the route we’ll use as a redirect:

import { redirectUnauthorizedTo, canActivate } from '@angular/fire/auth-guard';

const redirectUnauthorizedToLanding = redirectUnauthorizedTo(['landing']);

And our last step is to protect our route:

import { NgModule } from '@angular/core';
import { PreloadAllModules, RouterModule, Routes } from '@angular/router';
import { redirectUnauthorizedTo, canActivate } from '@angular/fire/auth-guard';

const redirectUnauthorizedToLanding = redirectUnauthorizedTo(['landing']);

const routes: Routes = [
  { path: '', redirectTo: 'home', pathMatch: 'full' },
  {
    path: 'home',
    loadChildren: './home/home.module#HomePageModule',
    ...canActivate(redirectUnauthorizedToLanding)
  }
];

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

And that’s it!

Do let me know what you think about it, I found it amazing and started updating several apps, which means deleting a bunch of code :-P

By the way, if you want to jump-start your app using Firebase check out my book Building Firestore Powered Ionic Apps