Auth Guards in angular
Renuka Patil

Renuka Patil @renukapatil

About: Interested in cloud computing, DevOps and microservices.

Location:
Pune, India
Joined:
Mar 7, 2022

Auth Guards in angular

Publish Date: Jul 7
5 0

In Angular, Auth Guards are used to protect routes from unauthorized access — a key feature when building secure applications.

Let’s break it down simply and show how to implement it 🔐


🔰 What is an Auth Guard in Angular?

An Auth Guard is a service that implements interfaces like:

  • CanActivate
  • CanActivateChild
  • CanLoad
  • CanDeactivate

Auth guards decide whether a user can or cannot access a route based on some logic — usually login status or roles.


🛡 Common Guard Types

Interface Use Case
CanActivate Checks access before loading a route
CanActivateChild Checks access for child routes
CanLoad Prevents lazy-loaded modules from even being loaded
CanDeactivate Confirms navigation away from the component

🧑‍💻 Create an Auth Guard

1. Generate the guard

ng generate guard auth
Enter fullscreen mode Exit fullscreen mode

2. Implement CanActivate interface

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;
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

auth.service.ts might look like:

isLoggedIn(): boolean {
  return !!localStorage.getItem('token');
}
Enter fullscreen mode Exit fullscreen mode

🛣 Apply the Guard to Routes

In your app-routing.module.ts:

import { AuthGuard } from './auth.guard';

const routes: Routes = [
  {
    path: 'dashboard',
    component: DashboardComponent,
    canActivate: [AuthGuard]
  },
  {
    path: 'login',
    component: LoginComponent
  }
];
Enter fullscreen mode Exit fullscreen mode

🧠 Bonus: CanLoad Example (Lazy Loaded Modules)

canLoad(route: Route): boolean {
  return this.authService.isLoggedIn();
}
Enter fullscreen mode Exit fullscreen mode

Apply it like:

{
  path: 'admin',
  loadChildren: () => import('./admin/admin.module').then(m => m.AdminModule),
  canLoad: [AuthGuard]
}
Enter fullscreen mode Exit fullscreen mode

✅ Summary

  • Auth Guards are services that protect routes.
  • They use interfaces like CanActivate, CanLoad, etc.
  • They help you redirect users to login if they're not authorized.

Happy Coding!

Comments 0 total

    Add comment