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! 🎯
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. 📝
To create a route guard, follow these steps:
ng generate service authGuardRouter and ActivatedRoute in the auth guard: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
}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.
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;
}Finally, use the auth guard in your route configuration:
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. ✅
You can create multiple route guards to handle different scenarios, such as role-based access control.
What is the purpose of a route guard in an Angular application?