Skip to content

Lab 07: Auth Guard

step-5-album-wholesale-v16-post-add-custom-async-validator

Continue from your previous lab result. If you need a fresh copy, use step-5-album-wholesale-v16-post-add-custom-async-validator as your base and complete Labs 05 and 06 first.

In this lab, you’ll implement route protection using a functional auth guard. You’ll create a CanActivate guard to restrict access to authenticated users, build a simple authentication service with login logic, and redirect unauthorized users to the login page.

Create a guard to protect routes:

import { inject } from '@angular/core';
import { Router, CanActivateFn } from '@angular/router';
export const authGuard: CanActivateFn = (route, state) => {
const authService = inject(AuthService);
const router = inject(Router);
if (authService.isLoggedIn()) {
return true;
}
return router.createUrlTree(['/login']);
};

Add guard to route configuration:

const routes: Routes = [
{
path: 'albums/add',
component: AlbumAddComponent,
canActivate: [authGuard]
}
];

Implement authentication logic:

@Injectable({ providedIn: 'root' })
export class AuthService {
private isAuthenticated = signal(false);
login(username: string, password: string): boolean {
if (username === 'admin' && password === 'admin') {
this.isAuthenticated.set(true);
return true;
}
return false;
}
isLoggedIn(): boolean {
return this.isAuthenticated();
}
}