Home Angular How to protect Angular routes with a guard?

How to protect Angular routes with a guard?

by therichpost
0 comments
How to protect Angular routes with a guard?

In Angular, protecting routes with a guard involves creating a service that implements the CanActivate interface from the @angular/router package. This service will define the logic to determine if a route can be activated based on certain conditions, such as user authentication status. Here’s a step-by-step guide on how to protect routes using a guard:

1. Generate a Guard Service

First, generate a guard service using the Angular CLI. Replace your-guard with a meaningful name for your guard.

ng generate guard your-guard

2. Implement CanActivate Interface

The CLI will ask you which interfaces you want to implement. Choose CanActivate. Then, implement the canActivate method in your guard service. Here’s an example where we check if the user is authenticated:

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, Router } from '@angular/router';
import { Observable } from 'rxjs';

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

  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {

    const isAuthenticated = this.checkIfUserIsAuthenticated(); // Implement this method based on your auth logic

    if (!isAuthenticated) {
      this.router.navigate(['/login']); // Redirect to login if not authenticated
      return false;
    }

    return true;
  }

  private checkIfUserIsAuthenticated(): boolean {
    // Your authentication logic here
    return false; // Example: default to false
  }
}

3. Protect a Route

After creating the guard, you can use it to protect specific routes in your app-routing.module.ts. Add the canActivate property to the route you want to protect and assign your guard service to it:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { YourComponent } from './your-component/your-component.component';
import { YourGuardService } from './path-to-your-guard/your-guard.service';

const routes: Routes = [
  { 
    path: 'protected-path',
    component: YourComponent,
    canActivate: [YourGuardService] // Protecting this route
  }
  // other routes...
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

4. Adjust Your Authentication Logic

Inside your guard service, adjust the checkIfUserIsAuthenticated method to correctly reflect your application’s authentication logic. This might involve checking if a user token exists in local storage, or if the user’s session is valid according to your backend.

5. Redirect Unauthenticated Users

Ensure your guard service properly redirects unauthenticated users to a login page or any other route intended for unauthorized access.

By following these steps, you can effectively protect specific routes in your Angular application using guards. This mechanism is highly customizable, allowing you to implement complex authentication and authorization logic to secure your routes.

You may also like

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.