Wednesday, 9 January 2019

Angular 6 Auth Guards / Route Guards - The Magic Autharization

What are Route Guards?

Angular’s route guards are interfaces which can tell the router whether or not it should allow navigation to a requested route. They make this decision by looking for a true or false return value from a class which implements the given guard interface.

There are five different types of guards and each of them is called in a particular sequence. The router’s behavior is modified differently depending on which guard is used.

The guards are:

  1. CanActivate
  2. CanActivateChild
  3. CanDeactivate
  4. CanLoad
  5. Resolve

Create a new service which implements the route guard. You can call it whatever you like, but something like auth-guard.service is generally sufficient.

  // src/app/auth/auth-guard.service.ts
import { Injectable } from '@angular/core';
import { Router, CanActivate } from '@angular/router';
import { AuthService } from './auth.service';
export class AuthGuardService implements CanActivate {
  constructor(public auth: AuthService, public router: Router) {}
  canActivate(): boolean {
    if (!this.auth.isAuthenticated()) {
      return false;
    return true;

The service injects AuthService and Router and has a single method called canActivate. This method is necessary to properly implement the CanActivate interface.

The canActivate method returns a boolean indicating whether or not navigation to a route should be allowed. If the user isn’t authenticated, they are re-routed to some other place, in this case a route called /login.

Now the guard can be applied to any routes you wish to protect.

  // src/app/app.routes.ts
import { Routes, CanActivate } from '@angular/router';
import { ProfileComponent } from './profile/profile.component';
import { 
  AuthGuardService as AuthGuard 
} from './auth/auth-guard.service';
export const ROUTES: Routes = [
  { path: '', component: HomeComponent },
    path: 'profile',
    component: ProfileComponent,
    canActivate: [AuthGuard] 
  { path: '**', redirectTo: '' }

The /profile route has an extra config value now: canActivate. The AuthGuard that was created above is passed to an array for canActivate which means it will be run any time someone tries to access the /profile route. If the user is authenticated, they get to the route. If not, they are redirected to the /login route.