Skip to main content

Lab 07: Auth Guard

πŸ“– Resources​

πŸš€ Starter Code​

step-7-album-wholesale-v16-onpush

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.

πŸ“ Instructions​

Step 1: Create Auth Guard​

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']);
};

Step 2: Apply to Routes​

Add guard to route configuration:

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

Step 3: Create Auth Service​

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();
}
}