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