Angular Firebase Auth Guards (Easy Guide)


Today we're going to learn how to use Angular Firebase Authentication and Angular's Route Guard feature to secure an app.

We'll be looking at how to use the Angular Firebase AuthGuard to secure an Angular app.

In other words, Angular + Firebase Authentication + Route Guards = 🔒 🔒 🔒.

guard

This assumes that you've already installed Angular Firebase to your project and configured Firebase Authentication.

Let's get into this!

Angular Route Guard with Firebase Authentication

To start with, we can import the Angular Firebase AuthGuard and use it as a built-in route guard.

Our routes file would look like this.

import { Routes } from '@angular/router';
import { AuthGuard } from '@angular/fire/auth-guard';
import { MainLayoutComponent } from './layouts/main-layout/main-layout.component';
import { dashboardRoutes } from './features/dashboard/dashboard.routes';
import { AuthLayoutComponent } from './layouts/auth-layout/auth-layout.component';
import { authRoutes } from './features/auth/auth.routes';

export const routes: Routes = [
    {
        path: 'auth',
        component: AuthLayoutComponent,
        children: authRoutes
    },
    {
        path: 'app',
        component: MainLayoutComponent,
        canActivate: [AuthGuard],
        children: dashboardRoutes
    }
];

This will make so that only users that are authenticated with our Firebase project are allowed to access our app.

2. Use Angular Route Guard to Redirect to Login Page

But what if we want to redirect an un-authenticated user to the login page if they try to access a restricted component?

redirecting

We can use the redirectUnauthorizedTo function.

import { Routes } from '@angular/router';
import { AuthGuard, redirectUnauthorizedTo } from '@angular/fire/auth-guard';
import { MainLayoutComponent } from './layouts/main-layout/main-layout.component';
import { dashboardRoutes } from './features/dashboard/dashboard.routes';
import { AuthLayoutComponent } from './layouts/auth-layout/auth-layout.component';
import { authRoutes } from './features/auth/auth.routes';

const redirectUnauthorizedToLanding = () => redirectUnauthorizedTo(['auth', 'login']); 

export const routes: Routes = [
    {
        path: 'auth',
        component: AuthLayoutComponent,
        children: authRoutes
    },
    {
        path: 'app',
        component: MainLayoutComponent,
        children: [dashboardRoutes ],
        canActivate: [AuthGuard], data: { authGuardPipe: redirectUnauthorizedToLanding }
    },
];

Now that anyone tries to access the restricted part of our app will now be redirected to the /auth/login route where they can login.

Conclusion

And that, my Angular friend, is how to use Angular Firebase and Angular route guards to secure your Angular app with Firebase Authentication.

Got any questions?

Don't hesitate to reach out!

Till later,

signature

Daniel Kreider