How to Use Multiple Angular AuthGuards in canActivate | Step-by-Step Guide

Angular AuthGuards are a powerful feature of Angular’s routing system that allows developers to control access to routes and resources based on a user’s authentication status and other criteria. By default, a route can have only one AuthGuard assigned to it in the canActivate property. But what if you need to ensure that a user meets multiple criteria before accessing a specific route or resource?

In this post, we’ll show you how to implement multiple Angular AuthGuards in the canActivate guard. You’ll learn how to chain AuthGuards together, use them in conjunction with other guards, and create your own custom guards to meet your application’s specific needs.

How to Use Multiple Angular AuthGuards in canActivate
How to Use Multiple Angular AuthGuards in canActivate

Can I use Multiple Angular AuthGuards in canActivate?

Yes, you can use more than one AuthGuard in the canActivate guard of an Angular route. In fact, it’s quite common to use multiple AuthGuard implementations to ensure that a user meets multiple criteria before accessing a specific route or resource.

To use multiple AuthGuard implementations in canActivate, you simply need to provide an array of AuthGuard instances to the canActivate property of the route definition.

Here’s an example:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AuthGuard } from './auth.guard';
import { AdminGuard } from './admin.guard';
import { DashboardComponent } from './dashboard/dashboard.component';

const routes: Routes = [
  {
    path: 'dashboard',
    component: DashboardComponent,
    canActivate: [AuthGuard, AdminGuard]
  }
];

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

In this example, the canActivate property of the /dashboard the route is set to an array containing two AuthGuard instances: AuthGuard and AdminGuard. This means that the user must pass both guards to access the /dashboard route.

We will redirect the user to the default route for unauthorized users if either of the guards fail.

Here is an example implementation of AuthGuard and AdminGuard:

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

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

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    if (this.authService.isLoggedIn()) {
      return true;
    } else {
      this.router.navigate(['/login']);
      return false;
    }
  }
}

In this example, AuthGuard is checking if the user is logged in by calling the isLoggedIn() method of an AuthService instance. If the user is not logged in, AuthGuard redirects the user to the /login page.

And here’s an example implementation of AdminGuard:

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

@Injectable({
  providedIn: 'root'
})
export class AdminGuard implements CanActivate {
  constructor(private authService: AuthService, private router: Router) {}

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    if (this.authService.isAdmin()) {
      return true;
    } else {
      this.router.navigate(['/']);
      return false;
    }
  }
}

In this example, AdminGuard is checking if the user is an admin by calling the isAdmin() method of the same AuthService instance. If the user is not an admin, AdminGuard redirects the user to the default page.

Here is an example implementation of an AuthService:

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  private isLoggedInVar: boolean = false;
  private isAdminVar: boolean = false;

  constructor() { }

  login(username: string, password: string): boolean {
    // Perform authentication logic here
    // If successful, set isLoggedInVar and isAdminVar to true if necessary
    // Return true if authentication was successful, false otherwise
  }

  logout(): void {
    this.isLoggedInVar = false;
    this.isAdminVar = false;
    // Perform any necessary cleanup here
  }

  isLoggedIn(): boolean {
    return this.isLoggedInVar;
  }

  isAdmin(): boolean {
    return this.isAdminVar;
  }
}

In this example, AuthService has a login() the method that performs the authentication logic. If authentication is successful, it sets isLoggedInVar and isAdminVar to true if necessary. AuthService also has a logout() the method that clears the isLoggedInVar and isAdminVar flags. Finally, AuthService has two methods isLoggedIn() and isAdmin() that return the values of isLoggedInVar and isAdminVar respectively.

This is just a simple example, of course. In a real application, you would likely implement more complex logic for authentication and authorization.

For more details, visit the official site of Angular

Check out other topics that might interest you.

Conclusion:

In conclusion, using multiple Angular AuthGuards in canActivate is a powerful way to control access to routes and resources in your application. By chaining AuthGuards together or using them in conjunction with other guards, you can ensure that your users meet all of the necessary criteria before accessing sensitive data or functionality. And by creating your own custom guards, you can tailor your application’s security to meet your specific needs. With the knowledge you’ve gained from this post, you’ll be able to create more secure and user-friendly applications with Angular.

Leave a Reply

Your email address will not be published. Required fields are marked *

Verified by MonsterInsights