All Course > Angular > Routing And Navigation Feb 16, 2025

Protecting Angular Routes with Guards: A Step-by-Step Guide

In the last lesson, we learned how to set up Angular routing, which allows users to navigate between different parts of a web app. Now, it’s time to take routing a step further by protecting routes with guards. Route guards help control who can access certain parts of your app, ensuring only authorized users can view specific pages. This is especially useful for apps that require user login or role-based access.

In this lesson, we’ll dive into Angular route guards, focusing on AuthGuard and CanActivate. By the end, you’ll know how to implement route guards to secure your app and restrict access based on user roles. Let’s get started!

Why Route Guards Matter

When I first built a web app for a client, I faced a common issue: unauthorized users could access sensitive pages simply by typing the URL. This was a big problem because the app stored private user data. I needed a way to block access to certain routes unless the user was logged in. That’s when I discovered Angular route guards.

Route guards are like security checkpoints for your app. They decide whether a user can access a route, leave a route, or load data for a route. For example, if a user tries to visit a dashboard page without logging in, the guard can redirect them to the login page. This ensures only the right people can access the right content.

How to Use CanActivate in Angular

The CanActivate guard is one of the most commonly used route guards. It checks if a user can access a specific route. Let’s say you have an admin dashboard that only logged-in users should see. Here’s how you can use CanActivate to protect it:

Create an AuthGuard Service

First, generate a guard using the Angular CLI:

ng generate guard auth

This creates a file named auth.guard.ts. Open it and add the following code:

import { Injectable } from '@angular/core';  
import { CanActivate, 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(): boolean {  
    if (this.authService.isLoggedIn()) {  
      return true;  
    } else {  
      this.router.navigate(['/login']);  
      return false;  
    }  
  }  
}  

In this example, the canActivate method checks if the user is logged in using a method from AuthService. If not, it redirects them to the login page.

Apply the Guard to Routes

Next, apply the guard to the routes you want to protect. Open your app-routing.module.ts file and add the guard to the route configuration:

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

Now, only logged-in users can access the dashboard.

Role-Based Access Control in Agular

Sometimes, you need to restrict access based on user roles. For example, an admin might have access to more features than a regular user. To implement role-based access, you can extend the AuthGuard to check the user’s role.

Here’s an example:

canActivate(): boolean {  
  if (this.authService.isLoggedIn() && this.authService.getUserRole() === 'admin') {  
    return true;  
  } else {  
    this.router.navigate(['/unauthorized']);  
    return false;  
  }  
}

In this code, the guard checks if the user is both logged in and has the role of “admin.” If not, it redirects them to an “unauthorized” page.

Practical Use Case: Protecting a Profile Page

Let’s say you’re building a social media app with a profile page that only the user can access. Here’s how you can protect it:

Create a ProfileGuard

Generate a new guard for the profile page:

ng generate guard profile  

Then, modify the canActivate method to check if the current user matches the profile owner:

canActivate(route: ActivatedRouteSnapshot): boolean {  
  const userId = route.params['id'];  
  if (this.authService.getCurrentUserId() === userId) {  
    return true;  
  } else {  
    this.router.navigate(['/unauthorized']);  
    return false;  
  }  
}  

Apply the Guard

Add the guard to the profile route:

{ path: 'profile/:id', component: ProfileComponent, canActivate: [ProfileGuard] }  

Now, only the profile owner can access their profile page.

Conclusion

In this lesson, we explored how to protect Angular routes using guards. We covered CanActivate, AuthGuard, and role-based access control. By implementing these guards, you can ensure that only authorized users can access specific parts of your app.

If you’re ready to take your Angular skills to the next level, check out the next lesson on Making HTTP Requests in Angular. You’ll learn how to fetch data from APIs and handle responses like a pro.

Comments

There are no comments yet.

Write a comment

You can use the Markdown syntax to format your comment.

Tags: angular typescript