🔐 Secure Your Angular Routes with CanActivate: A Complete Guide

In any modern Angular application, controlling access to routes is more than just a best practice—it’s essential for security and a smooth user experience. That’s where CanActivate comes in.

Whether you’re protecting admin dashboards, user profiles, or feature pages, CanActivate lets you guard routes and restrict access based on conditions like authentication status or user roles. Let’s walk through how it works and how to implement it effectively in your Angular project.


🚧 What is CanActivate in Angular?

CanActivate is a type of route guard in Angular. It decides if a route can be activated (i.e., navigated to) before the component is loaded.

💡 Why Use CanActivate?

  • ✅ Block access to restricted pages
  • ✅ Enforce role-based access control (RBAC)
  • ✅ Improve UX by redirecting unauthorized users
  • ✅ Prevent unauthorized API calls and page access

🔨 Step-by-Step: Implementing CanActivate


🧰 Step 1: Create an Authentication Service

This service manages whether a user is logged in and what their role is:

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

@Injectable({ providedIn: 'root' })
export class AuthService {
private isAuthenticated = false;
private userRole: string | null = null;

login(role: string) {
this.isAuthenticated = true;
this.userRole = role;
}

logout() {
this.isAuthenticated = false;
this.userRole = null;
}

isUserAuthenticated(): boolean {
return this.isAuthenticated;
}

getUserRole(): string | null {
return this.userRole;
}
}

🛡️ Step 2: Create the Auth Guard (CanActivate)

Your guard will implement the logic to allow or block access:

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { AuthService } from './auth.service';

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

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
if (this.authService.isUserAuthenticated()) {
return true;
} else {
this.router.navigate(['/login']);
return false;
}
}
}

🗺️ Step 3: Apply the Guard to Routes

Secure your routes by adding canActivate to the relevant route definitions:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { DashboardComponent } from './dashboard/dashboard.component';
import { LoginComponent } from './login/login.component';
import { AuthGuard } from './auth.guard';

const routes: Routes = [
{ path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] },
{ path: 'login', component: LoginComponent },
{ path: '', redirectTo: '/login', pathMatch: 'full' }
];

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

🔐 Bonus: Role-Based Access with CanActivate

If you want to restrict routes based on roles (e.g., “admin”, “user”), you can pass role metadata via route data and check it inside the guard.

Update Guard Logic:

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
const expectedRole = route.data['role'];
const userRole = this.authService.getUserRole();

if (this.authService.isUserAuthenticated() && userRole === expectedRole) {
return true;
} else {
this.router.navigate(['/unauthorized']);
return false;
}
}

Define Roles in Your Routes:

const routes: Routes = [
{ path: 'admin', component: AdminComponent, canActivate: [AuthGuard], data: { role: 'admin' } },
{ path: 'user', component: UserComponent, canActivate: [AuthGuard], data: { role: 'user' } }
];

✅ Summary

CanActivate is your first line of defense for secure Angular routing. Whether you’re dealing with simple login checks or full-on role-based authorization, this guard helps keep the wrong users out of the wrong places.

By combining it with services and route metadata, you can create a flexible and secure access control system that scales with your app.

Leave a Comment

Your email address will not be published. Required fields are marked *