Innovate anywhere, anytime withruncode.io Your cloud-based dev studio.
Angular

Implementing Angular Permissions using Route AuthGuards

2022-07-16

In this blog, we'll see how to use Angular's route guards to help with authentication.

What are Route Guards?

Angular route guards are interfaces, which checks whether the router allows navigation for the user requested route.

There are different guard types we can use to protect our routes, each of then can be called on particular sequence:

  • CanActivate - Decides whether the requested route can be activated
  • CanActivateChild - Decides whether the children routes of a route can be activated
  • CanDeactivate - Decides whether the requested route can be deactivated
  • CanLoad - Decides if a module can be loaded lazily

Here we see an Example for canActivate guard type,

Eg: When a user is not authenticated and requested for the user dashboard route, we should not permit that route. the user can access that page only if a user is authenticated.

Let's create a component for the UserDashboard

ng g generate components/UserDashboard

Add userdashboard route in your application app.router.ts

import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { UserDashboardComponent } from './components/user-dashboard.component';

export const router: Routes = [
    {path: 'user-dashboard' , component: UserDashboardComponent},
];

Here we haven't given any authguards for route, So everyone can access this page without any permission.

Let's create a service component using below command

ng g service services/authguard

Now, this will add in your application app.module.ts in providers, So that we can use that service in your entire application.

import { Injectable } from '@angular/core';
import { Router, CanActivate } from '@angular/router';

@Injectable()
export class AuthGuard implements CanActivate {

  constructor(public router: Router) {}

  canActivate(): boolean {
   const token = localStorage.getItem('token');
    if (!token) {
      this.router.navigate(['login']);
      return false;
    }
    return true;
  }
}

Now, to provide permission for the specific route add this service for that route. At that time when a user hits the route first checks for the authguard based on the return response renders that page.

If it returns true, then page is visible for that user, otherwise user can't be visible that page

In your app.router.ts update the router with AuthGuard

import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { UserDashboardComponent } from './components/user-dashboard.component';
import { AuthGuard } from './services/authguard';

export const router: Routes = [
    {path: 'user-dashboard' , component: UserDashboardComponent, canActivate: [AuthGuard]},
];