Blog>
Snippets

Securing Angular Route Access with Route Guards

Create an example of a route guard to prevent unauthorized access to specific routes within an Angular application.
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {
  constructor(private router: Router) {}

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean> | Promise<boolean> | boolean {
    if (this.isLoggedIn()) {
      return true;
    }

    this.router.navigate(['/login']);
    return false;
  }

  private isLoggedIn(): boolean {
    // Replace with actual user authentication logic
    return !!localStorage.getItem('userToken');
  }
}
Defines an AuthGuard service that implements the CanActivate interface. The canActivate method is used to determine if a user can navigate to a route. It checks if the user is logged in (using a placeholder isLoggedIn function) and redirects to the login page if not authorized.
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AuthGuard } from './auth.guard';
import { ProtectedComponent } from './protected/protected.component';

const routes: Routes = [
  { path: 'protected', component: ProtectedComponent, canActivate: [AuthGuard] }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
Applies the AuthGuard to a route in the application's routing module. The AuthGuard is assigned to the canActivate property of the route definition. In this case, it secures the 'protected' route, which will render the ProtectedComponent only if the AuthGuard returns true.