Securing Angular 2 routes with Auth Guard through canActivate

I've been searching for a solution to this problem for the past 4 hours with no luck.

I have multiple Authguards set up, and I want to instruct the router to grant permission if any of them are true, rather than requiring all guards to be true. Currently, Angular 2 router checks each guard individually before granting permission or blocking access to the link. Is there a better way to approach this issue? Creating several Authentication guards doesn't seem like an ideal solution.

For instance, I want the /profile page to only be accessible by admin and super-user roles, not regular users.

Answer №1

Utilize a single parent Guard to manage multiple guards and retain control:

    @Injectable()
    class MasterGuard implements CanActivate {

      constructor(private firstGuard: Guard1, private secondGuard: Guard2) {}

      canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
        // Assuming that guard1.canActivate() and guard2.canActivate() return a boolean
        return this.firstGuard.canActivate() || this.secondGuard.canActivate();
      }
    }

In your route configuration, simply use the MasterGuard:

{
  path : 'route',
  canActivate : MasterGuard 
  ...
}

Feel free to utilize firstGuard and secondGuard in other routes as well.

Answer №2

If you want to control access to routes, you can utilize the CanLoad interface within an authentication guard. For instance, consider a route setup like this:

{
     path: 'dashboard',
     component: 'DashboardComponent',
     canLoad: [
          AuthGuard
     ]
}

To implement this in your AuthGuard, make sure to include the CanLoad interface. By doing so, if a user lacks permission for a particular route, the modules associated with that route will not load.

export class AuthGuard implements CanLoad {
     canLoad(route: Route): Observable<boolean> | Promise<boolean> | boolean {
          //Here, you would call on your authentication service to verify if the current user has access to this specific route
     }
}

I trust this explanation is helpful. If you have any more questions, feel free to reach out.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best approach to obtain complete and error methods from the server using BehaviorSubject?

Here is a description of my unique service: @Injectable() export class SettingService { private settings = new BehaviorSubject<any[]>([]); constructor(private http: HttpClient) { this.loadSettings(); } private loadSettings( ...

"Error encountered: Array is undefined when using the map and subscribe functions in Ionic

I have developed a service that is supposed to retrieve data from a JSON file and assign it to an array called 'countries', which will be used throughout the application on multiple pages. However, when I call the method getCountries, the countri ...

React's useState feature is doubling the increment

I have created a basic form management system with a historical feature. A simplified version of this system can be seen on codesandbox import { useState } from "react"; import "./styles.css"; const sample = ["what", "w ...

CORS policy issue with Angular incorporating Agora shows "No 'Access-Control-Allow-Origin'"

I'm new to Angular and currently working on a demo app for proof of concept. The main focus is integrating the Agora SDK into Angular for video calls. I found an integration code for Agora in Angular on GitHub and implemented it as shown below. The `s ...

Creating a helper function for initiating and ending loading using Angular2's Observable forkJoin

I have a question regarding the forkjoin method in Angular. My main concern is writing a helper function that can handle multiple observables. This helper function should display a spinner service before subscribing to the observables and then hide the spi ...

Expiry Time for JWT Token (ASP.NET Core)

I've been trying to extend the lifespan of JWT tokens without success. After researching online, I came across information about JwtBearerOptions.TokenValidationParameters.ClockSkew. I attempted to set timespans of 1 minute and 20 seconds, but the a ...

ANGULAR: Issue with filtering an array by clicking a button is not functioning

I've been attempting to apply a filter to my array by using modulo on the id when clicking multiple buttons. I initially tried using pipe but was advised to stick with .filter(). Despite watching numerous online tutorials, I keep encountering errors o ...

Upon updating my Angular application from version 5.2 to the most recent one, I encountered an ERROR when running ng build

There was an error in the file ./src/styles.css (./node_modules/@angular-devkit/build-angular/src/angular-cli-files/plugins/raw-css-loader.js!./node_modules/postcss-loader/src??embedded!./src/styles.css) The module build failed due to a SyntaxError (60: ...

How can I swap a string for a symbol in JavaScript?

Is there a way to convert the text @abc some text here to <a href="some_url">@abc</a> some text here using JavaScript? Are there any libraries that can help with this task? ...

What is the source of the compiler options in tsconfig.json?

Currently utilizing Typescript in NestJs, I have incorporated various packages. However, the specific package responsible for altering these settings remains unknown to me: "checkJs": false, "skipLibCheck": true Is there a method to ...

Encountering an error of incorrect format while attempting to ssh into an Azure NextGen VM created by P

Having some trouble creating and sshing into a virtual machine using the Azure nextgen Pulumi API on my Windows 10 machine. After successfully creating the VM, I export the private key to a file for testing purposes. I then adjust the permissions to preve ...

The Mat-Datepicker will always show the current date in your local time zone, never in

Utilizing a datepicker and momentjs, I have successfully implemented sending UTC dates to my server. However, the issue arises when retrieving these UTC dates back into the date picker, as it always reflects my timezone (EST). This discrepancy can result i ...

Develop a novel object framework by merging correlated data with identical keys

I am trying to organize the related data IOrderData by grouping them based on the productId and brandId. This will help create a new array of objects called IOrderTypeData, where the only difference between the objects is the delivery type. Each product id ...

The optimal time to register for events within the Vue lifecycle

Currently, I am developing a Vue2 component using vue-component that includes a subcomponent. Here is an example: <note :bus="bus" :itemId="selectedId"></note> The subcomponent contains the following code snippet: <textarea v-model="text" ...

What exactly does the statement if(item.some((item) => !item.available) represent in typescript?

Can you explain the meaning of if(item.some((item) => !item.available))? While looking at some code randomly, I came across this snippet: if(item.some((item) => !item.available){ } I'm curious about what it signifies. Can you elaborate on it? ...

Generate a basic collection of strings from an object

Looking at this object structure Names = [ { group: 'BII', categories: null }, { group: 'GVL', categories: [] } ]; I ...

Encountering an issue of THREE.EventDispatcher being undefined while trying to create a THREE.OrbitControls instance using THREE.js, THREE.OrbitControls, and TypeScript

Attempting to delve into typescript alongside three.js, I've encountered a perplexing error that has me stumped. The root of the issue lies within the init function where I initialize a new THREE.OrbitControls controller. Utilizing the setup provided ...

Encountering difficulties when attempting to include Spartacus in an Angular application

I'm having trouble integrating Spartacus into my Angular application Here are the steps I followed: Created an Angular application [ng new xyz --style=scss --routing=false] Added a .npmrc file. Ran: ng add @spartacus/[email protected] Now, I&a ...

The select dropdown default choice is not appearing as expected

My template is not showing the default select option that I have set for one select element. I attempted to achieve this with the following code: <div class="select"> <select (change)="calculaMes(mesEscolhido)" [(ngModel)]="mesEscolhido" na ...

Are 'const' and 'let' interchangeable in Typescript?

Exploring AngularJS 2 and Typescript led me to create something using these technologies as a way to grasp the basics of Typescript. Through various sources, I delved into modules, Typescript concepts, with one particularly interesting topic discussing the ...