Angular 2 and Firebase Authentication Route Guard

firebase Jan 12, 2018

Protecting routes is a very common task when building applications, as we want to prevent users from accessing specific areas that they’re not allowed to access such as a restricted area for members only. Angular’s router provides a feature called Navigation Guards that solve exactly that problem. I wanted to share one sample of code which works with Firebase to detect if a user is logged in or not, if not logged in, they are redirected to the login page. I have blogged before about Firebase, it is a great backend-as-a-service platform. This code example works with Angular 2 and Firebase 5.

As part of the Navigation Guards, is the CanActivate interface. This is used as to check a user is logged in or not. Our authorization process is built on observables, so we need to subscribe to the auth state of Firebase, then return true or false.

Below is an example of CanActivate being used to check if a user is logged in or not via Firebase.

To use the Guard in the router is very easy. We simply need to import the Guard and assign it to the routes that need protecting.

Remember to add this to add the Guard as a provider in app.module.ts. And that is it, you are now able to protect your routes.

A key take home message is that Authentication Route guard is only partly secure. As we can see above, it is code served client side. If the user could temper with the source code they could potentially change the way it works. While the source code may be minified or uglified at the heart of it is still a bunch of HTML/JS/CSS files. Anyone who knows the URL can download the source.

It is important that the backend is secured, as it does the bulk of the protecting. In the case of Firebase, it is ensuring that permission rules on the database have been crafted correctly. It is important to think about security early on in the development cycle, it can be troublesome to include further down the development cycle.