Angular Tutorial: Route Guards for Auth

beginner
24 min

Angular Tutorial: Route Guards for Auth

Welcome to our comprehensive guide on Angular Route Guards for Authentication! In this lesson, we'll learn how to secure our Angular applications using route guards. Let's dive in! 🎯

Understanding Route Guards

Route guards are Angular services that can intervene in the navigation process to determine whether the transition should be allowed or not. They are used to protect routes that require authentication. 📝

Creating a Route Guard

To create a route guard, follow these steps:

  1. Create a new service using Angular CLI:
bash
ng generate service authGuard
  1. Inject the Router and ActivatedRoute in the auth guard:
typescript
import { Injectable } from '@angular/core'; import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router'; @Injectable({ providedIn: 'root' }) export class AuthGuard implements CanActivate { constructor(private router: Router) {} // Implement CanActivate method here }

Implementing CanActivate Method

The CanActivate interface contains a single method canActivate(), which must return an Observable<boolean> or Promise<boolean>. This method is responsible for determining whether the user is authenticated or not.

typescript
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | Observable<boolean> | Promise<boolean> { // Check for authentication here, e.g., by checking if user is logged in // If the user is not authenticated, redirect them to the login page if (!isAuthenticated()) { this.router.navigate(['/login']); return false; } // If the user is authenticated, allow the navigation return true; }

Using the Auth Guard

Finally, use the auth guard in your route configuration:

typescript
import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { AuthGuard } from './auth.guard'; const routes: Routes = [ { path: 'protected', canActivate: [AuthGuard], component: ProtectedComponent }, // Add more routes here ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }

Now, when a user tries to access the protected route, the auth guard will check if they are authenticated. If they are not, they will be redirected to the login page. ✅

Pro Tip:

You can create multiple route guards to handle different scenarios, such as role-based access control.

Quiz

Quick Quiz
Question 1 of 1

What is the purpose of a route guard in an Angular application?