Skip to main content

Overview

The authGuard is an Angular route guard that ensures only authenticated users can access protected routes. It checks for the presence of a valid authentication token and redirects unauthenticated users to the login page.

Signature

Type Definition

Implementation

Parameters

ActivatedRouteSnapshot
Contains information about the route being activated
RouterStateSnapshot
Contains the router state at a particular moment in time

Return Value

boolean
  • true - User is authenticated, allow access to the route
  • false - User is not authenticated, redirect to /auth/login

Usage

Route Configuration

Apply the authGuard to routes that require authentication:

Protecting Multiple Routes

You can apply the guard to a parent route to protect all child routes:

How It Works

  1. Token Check: The guard retrieves the authentication token from TokenStorageService
  2. Validation: If a token exists, the user is considered authenticated
  3. Access Control:
    • Authenticated: Returns true, allowing navigation to proceed
    • Not Authenticated: Redirects to /auth/login and returns false

Dependencies

  • TokenStorageService (src/app/core/guards/auth-guard.ts:7): Service for managing authentication tokens
  • Router (src/app/core/guards/auth-guard.ts:8): Angular router for navigation
This guard uses Angular’s modern functional guard approach (introduced in Angular 14+) instead of the older class-based guard pattern.
The guard only checks for the presence of a token, not its validity. If your token can expire, consider implementing token validation or refresh logic in the TokenStorageService.

When to Use

Use authGuard when you need to:
  • Protect routes that require any authenticated user (regardless of role)
  • Prevent anonymous users from accessing protected resources
  • Automatically redirect unauthenticated users to the login page
For role-based access control, see adminGuard.