0
0
AngularHow-ToBeginner · 4 min read

How to Create Auth Guard in Angular: Step-by-Step Guide

In Angular, create an auth guard by implementing the CanActivate interface in a service that checks user authentication before allowing route access. Register this guard in your routing module using the canActivate property on routes you want to protect.
📐

Syntax

An auth guard in Angular is a service that implements the CanActivate interface. It must have a canActivate method that returns true to allow navigation or false to block it. You then apply this guard to routes in your routing module using the canActivate array.

  • CanActivate interface: Defines the method to decide if a route can be activated.
  • canActivate method: Returns a boolean or an Observable/Promise resolving to boolean.
  • Route configuration: Use canActivate: [YourAuthGuard] to protect routes.
typescript
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree } from '@angular/router';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {
  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): boolean | UrlTree | Observable<boolean | UrlTree> | Promise<boolean | UrlTree> {
    // Your auth logic here
    return true; // or false
  }
}

// In your routing module
const routes = [
  {
    path: 'protected',
    component: ProtectedComponent,
    canActivate: [AuthGuard]
  }
];
💻

Example

This example shows a simple auth guard that allows access only if the user is logged in. The guard uses a fake AuthService to check login status. The canActivate method returns true if logged in, otherwise it redirects to the login page and returns false.

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

@Injectable({ providedIn: 'root' })
export class AuthService {
  private loggedIn = false;

  isLoggedIn(): boolean {
    return this.loggedIn;
  }

  login() {
    this.loggedIn = true;
  }

  logout() {
    this.loggedIn = false;
  }
}

@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;
    }
  }
}

// Routing module snippet
import { Routes } from '@angular/router';
import { ProtectedComponent } from './protected.component';
import { LoginComponent } from './login.component';

export const routes: Routes = [
  { path: 'login', component: LoginComponent },
  { path: 'protected', component: ProtectedComponent, canActivate: [AuthGuard] },
  { path: '', redirectTo: '/login', pathMatch: 'full' }
];
Output
When navigating to '/protected', if user is logged in, the ProtectedComponent displays; otherwise, user is redirected to '/login'.
⚠️

Common Pitfalls

  • Not providing the guard service: Forgetting to add @Injectable({ providedIn: 'root' }) or to register the guard in the module can cause errors.
  • Returning wrong types: canActivate must return a boolean, UrlTree, or Observable/Promise of these; returning other types causes runtime errors.
  • Not handling asynchronous checks: If auth status is async, you must return an Observable or Promise, not just a boolean.
  • Forgetting to import Router: Needed to redirect unauthenticated users.

Example of a wrong and right canActivate method:

typescript
canActivate(): boolean {
  // Wrong: returning a string instead of boolean
  return 'yes';
}

canActivate(): boolean {
  // Right: returns boolean
  return true;
}
📊

Quick Reference

Use this quick checklist when creating an auth guard:

  • Implement CanActivate interface in a service.
  • Return true to allow or false (or redirect) to block route access.
  • Apply guard in routing module with canActivate: [YourGuard].
  • Handle async auth checks with Observables or Promises.
  • Inject Router to redirect unauthorized users.

Key Takeaways

Create an auth guard by implementing the CanActivate interface in a service.
Return true to allow route access or false (with optional redirect) to block it.
Apply the guard to routes using the canActivate property in your routing module.
Handle asynchronous authentication checks by returning Observables or Promises.
Always inject Router to redirect unauthorized users to login or other pages.