Using Route Guards for Access Control

Tutorial 2 of 5

1. Introduction

In this tutorial, we will explore how to use route guards in Angular for access control. Route guards are a powerful feature in Angular that allows us to control access to certain routes based on user authentication or permissions. After completing this tutorial, you will have a good understanding of how to implement route guards in your Angular applications.

What Will You Learn?

  • What are route guards in Angular
  • How to use route guards to control access to routes based on authentication and permissions

Prerequisites

  • Basic understanding of Angular and TypeScript
  • Familiarity with Angular routing

2. Step-by-Step Guide

Angular provides several types of route guards, but the most commonly used are CanActivate and CanLoad. CanActivate determines if a route can be activated, and CanLoad determines if a module can be loaded lazily.

Creating a Route Guard

  1. To create a guard, we use Angular CLI's ng generate guard command. Let's create a guard called auth.
ng generate guard auth
  1. This command will create a new file auth.guard.ts and will ask which interfaces you would like to implement.

  2. For this tutorial, we will implement the CanActivate interface.

Implementing the Guard

  1. Inside the auth.guard.ts file, we will implement a simple authentication check.
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {
  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): boolean {
    // Here we will check if the user is authenticated
    // For now, we will just return true
    return true;
  }
}
  1. In a real-world scenario, you would replace the return true; line with your own authentication logic.

3. Code Examples

Using the Guard in a Route

  1. Now that we have our guard, we can use it to protect our routes. Let's protect a route called /dashboard.
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { DashboardComponent } from './dashboard/dashboard.component';
import { AuthGuard } from './auth.guard';

const routes: Routes = [
  {
    path: 'dashboard',
    component: DashboardComponent,
    canActivate: [AuthGuard]
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
  1. Here, we added canActivate: [AuthGuard] to our /dashboard route. This means that before this route can be activated, the AuthGuard's canActivate method will be called.

Implementing a Real Authentication Check

  1. Let's implement a real authentication check in our AuthGuard. We will use a simple AuthService that we will create.
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  isAuthenticated(): boolean {
    // Here you should implement your authentication logic
    // For now, we will just return true
    return true;
  }
}
  1. Now, let's use this AuthService in our AuthGuard.
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { AuthService } from './auth.service';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {
  constructor(private authService: AuthService) {}

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): boolean {
    return this.authService.isAuthenticated();
  }
}

4. Summary

We have covered what route guards are in Angular and how to use them for access control. We created an AuthGuard and used it to protect our /dashboard route. We also created a simple AuthService and used it in our AuthGuard to implement a real authentication check.

5. Practice Exercises

  1. Create a CanLoad guard and use it to protect a lazily-loaded module.
  2. Implement a role-based guard that checks if a user has a certain role before a route can be activated.
  3. Use the Router service to redirect users to a /login page if they are not authenticated.

Remember, the key to mastering Angular route guards is practice and experimentation. Happy coding!