Implement CanActivate route guard in Angular – Auth Guard

 

Implement CanActivate route guard in Angular  – Auth Guard



Angular allows us to protect routes with guards. An angular Route guard is a way of protecting navigation by allowing or denying a route based on the condition we supply. The most commonly used angular route guard types are CanActivate and CanDeactivate. Angular has several guard interfaces that allow us to mediate navigation to and from a route.

Different types of Angular auth guard in Angular

ng g guard my-new-guard guard-type

CanActivate: Checks to see if we can visit a route based on condition.


First, you need to create a route guard. Run the following command in your terminal to generate a guard service:

ng g guard admin/admin


Two src/app/admin/admin.guard.spec.ts and src/app/admin/admin.guard.ts files will be generated. Open the src/app/admin/admin.guard.ts file, you should see the following code:


import { Injectable } from '@angular/core';

import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';

import { Observable } from 'rxjs';


@Injectable({

  providedIn: 'root'

})

export class AdminGuard implements CanActivate {

  canActivate(

    next: ActivatedRouteSnapshot,

    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {

    return true;

  }

}


Guard is simply a service that implements the CanActivate interface and overrides the canActivate() method.


Let's change the method to only allow access if the user is logged in. First, you need to import AuthService and inject it via the AdminGuard service and next you need to call the isLoggedIn property in the canActivate() method to check if the user is logged in and return true or false;


import { Injectable } from '@angular/core';

import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router, UrlTree } from '@angular/router';

import { Observable } from 'rxjs';

import { AuthService } from './auth/auth.service';


@Injectable({

  providedIn: 'root'

})

export class AdminGuard implements CanActivate {

  constructor(private authService: AuthService, private router: Router)

  {}

  canActivate(

    next: ActivatedRouteSnapshot,

    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean | UrlTree {

    if(this.authService.isLoggedIn){

      return true;

    }

    else{

      return this.router.parseUrl("/admin/login");

    }


  }

}



The canActivate() method will return true if the user is logged in or false otherwise.

The canActivate() method is passed many arguments which makes it easy to detrmine if the guard needs to allow or disallow access to certain route(s):

  1. next: ActivatedRouteSnapshotwhich is the next route that will be activated if the guard is allowing access,
  2. state: RouterStateSnapshotwhich is the next router state if the guard is allowing access.

Applying the Angular Guard



Now, you need to apply the guard to the routes you need to protect using the canActivate property of the path object. Open the src/app/admin/admin-routing.module.ts file and update it accordingly:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { ProjectComponent } from './project/project.component';
import { ProjectListComponent } from './project-list/project-list.component';
 
import { LoginComponent } from './login/login.component';
import { AdminGuard } from  './admin.guard';

const routes: Routes = [
    {
        path: 'project-dashboard',
        component: ProjectComponent,
        children: [
            {
                path: 'list',
                component: ProjectListComponent,
                canActivate: [AdminGuard]
            }
            { 
                path: 'login', 
                component: LoginComponent 
            }
        ]
    }
];


@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class AdminRoutingModule { }


Now, go to your application, if you visit any protected route without logging in you will be redirected to the /admin/login route where you can login.

Comments

Popular posts from this blog

Angular Best Practices and Coding Standards: A Guide for Developers

Route Web Server Request to App server through proxy

Top 7 ways to use Interceptors in Angular