Overview
TheauthGuard 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
Contains information about the route being activated
Contains the router state at a particular moment in time
Return Value
true- User is authenticated, allow access to the routefalse- User is not authenticated, redirect to/auth/login
Usage
Route Configuration
Apply theauthGuard 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
- Token Check: The guard retrieves the authentication token from
TokenStorageService - Validation: If a token exists, the user is considered authenticated
- Access Control:
- Authenticated: Returns
true, allowing navigation to proceed - Not Authenticated: Redirects to
/auth/loginand returnsfalse
- Authenticated: Returns
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.
When to Use
UseauthGuard 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
Related
- adminGuard - Role-based access control for admin users
- publicGuard - Prevents authenticated users from accessing public routes
- TokenStorageService - Token management service