Angular2: AuthGuard malfunctioning with browser navigation controls

My AuthGuard setup works flawlessly during normal navigation within the application (see code below).

Now, consider this scenario:

A user goes to /content/secured-content, which requires authentication => they are redirected to /authentication/login due to checkLogin => after successful authentication, they are redirected back to /content/secured-content => upon clicking "Logout" and logging out (checkLogin now returns false).

Here's where things get tricky: When the user revisits the secured content page using the browser's "back" button, neither canActivate, canActivateChild, nor canLoad gets triggered, allowing access to the secured content without re-authentication. I expect the user to be redirected to /authentication/login in such a case.

Could you point out my error in reasoning and suggest a proper solution?

Attachments

Routes configuration snippet:

{
  path: 'secured-content',
  component: SecureComponent,
  canLoad: [AuthGuard]
}

auth-guard.service.ts:

import { Injectable } from '@angular/core'
import { CanActivate, CanActivateChild, CanLoad,
    Router, ActivatedRouteSnapshot, RouterStateSnapshot, Route 
} from '@angular/router'

import { AuthenticationService } from 'app/authentication/authentication.service'

@Injectable()
export class AuthGuard implements CanActivate, CanActivateChild, CanLoad {
    constructor(
        private authService: AuthenticationService,
        private router: Router
    ) {}

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
        if (this.checkLogin(state.url)) {
            return true
        }
        return false
    }

    canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
        return this.canActivate(route, state)
    }

    canLoad(route: Route): boolean {
        const url = `/${route.path}`

        return this.checkLogin(url)
    }

    private checkLogin(url: string): boolean {
        if (this.authService.isAuthenticated()) {
            return true
        }

        this.authService.redirectUrl = url

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

ng --version:

@angular/cli: 1.0.1
node: 6.10.3
os: win32 x64
@angular/common: 4.1.2
@angular/compiler: 4.1.2
@angular/core: 4.1.2
@angular/forms: 4.1.2
@angular/http: 4.1.2
@angular/platform-browser: 4.1.2
@angular/platform-browser-dynamic: 4.1.2
@angular/router: 4.1.2
@angular/cli: 1.0.1
@angular/compiler-cli: 4.1.2

Answer №1

To enable route protection, you must include canActivate:[AuthGuard] in the routing setup.

Definition of canActivate:

This feature allows a class to act as a guard that determines whether a route can be activated or not.

Definition of canLoad:

Interface that enables a class to serve as a guard deciding if child routes can be loaded.

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

Instead of showing the data in the variable "ionic", there is a display of "[object object]"

Here is the code snippet I'm working with: this.facebook.login(['email', 'public_profile']).then((response: FacebookLoginResponse) => { this.facebook.api('me?fields=id,name,email,first_name,picture.width(720).height( ...

Using single-spa with Angular Parcel inside a mat-dialog

I have developed an Angular application and an Angular parcel that will be utilized by various applications within the organization utilizing different frameworks. When I try to display the parcel component directly in another component using the async c ...

extracting the value of an option from a form control to utilize in the component's model

I'm currently facing an issue where I am unable to retrieve the value of an option selection in my component class for further processing. Despite setting the value as [value]="unit" in the view, it still shows up as undefined when passed through onMo ...

Implement a grid control in Kendo-UI for Angular 2 that includes checkboxes in the first column

What is the process for adding a checkbox to the first column of a Kendo UI Angular2 grid? How can the checked status be retrieved for each row in the data? ...

Patience required for Angular to retrieve data from API call

I am currently struggling with getting my Donut chart to load properly with data returned from three separate API calls. I have initialized the chart and the API call functions in ngOninit(). However, it seems like my chart is not loading. I understand tha ...

Different Approaches to Authentication in Next.js

I've been working on establishing a secure authentication process for my Next.js project, but I'm feeling quite lost at the moment. Despite referencing the examples in the Next.js repository, I still have numerous queries regarding a comprehensiv ...

Using Angular NgUpgrade to inject an AngularJS service into an Angular service results in an error message stating: Unhandled Promise rejection: Cannot read property 'get' of undefined; Zone:

I have noticed several similar issues on this platform, but none of the solutions seem to work for me. My understanding is that because our Ng2App is bootstrapped first, it does not have a reference to $injector yet. Consequently, when I attempt to use it ...

Encountering a surprise token < while processing JSON with ASP.NET MVC alongside Angular

I encountered an issue when attempting to return the Index page. The data is successfully sent from the client to the server, but upon trying to display the Index page, an error occurs. Could someone review my code and identify where the mistake lies? acc ...

Integrate a formcontrol within a specialized directive

I am looking to develop a directive that can alter a host element when a form control is invalid. Here's an example in code: <div [appFormControlValidate]="email"> <!-- email is the form control I want to use --> <input type="email" ...

Angular 6 Time Discrepancy

I am trying to display real-time time difference on the UI that updates every second. Here is what I have attempted: component.ts import { Component, OnInit } from '@angular/core'; import 'rxjs/add/observable/of'; import 'rxjs/a ...

Leveraging NestJs Libraries within Your Nx Monorepo Main Application

I am currently part of a collaborative Nx monorepo workspace. The setup of the workspace looks something like this: https://i.stack.imgur.com/zenPw.png Within the structure, the api functions as a NestJS application while the data-access-scripts-execute ...

Angular 9 Issue: Failure to Display Nested Mat-Tree Children

Hello everyone, I'm new to posting questions on Stack Overflow and I'm seeking some assistance with an issue I'm having with Mat-Tree. Despite the fact that my data is present when I console log it, the children are not appearing. I am fetc ...

Utilizing Angular: Integrating the Http response output into a map

I have a situation where I am making multiple HTTP calls simultaneously from my Angular application. The goal is to store the responses of these calls in a Map. data: Map<number, any> = new map<number,any>(); --------------------------------- ...

The Validator.js module cannot be located - Unable to resolve 'http' in the client

Struggling with integrating the amadeus-node package into an angular 10 project. When I add the following line: const Amadeus = require('amadeus'); I encounter this error: ERROR in ./node_modules/amadeus/lib/amadeus/client/validator.js Module ...

Tips for updating the class of the body in an Angular 2 and Typescript project

When it comes to managing different classes for the login page versus other pages in an application, there is a need to change the body element's class once the user has logged in. Here is how I am attempting to achieve this: index.html <body [ng ...

Issue: Unhandled promise rejection: SecurityError: To use screen.orientation.lock(), the page must be in fullscreen mode

While attempting to change the orientation of one of my pages in an Ionic 3 app, I encountered the following error. The code snippet below was used to change from portrait mode to landscape mode: ionViewDidEnter() { // this.statusBar.hide(); // // ...

Facing problem with Angular 7 when making a GET request for non-JSON data

Currently, I am retrieving JSON data from a URL using the following method: this.http.get('http://localhost:3200/mydata').subscribe(data => { console.log(data); }); The response is in JSON format, and everything seems to be working fine. ...

Changes on services do not affect the Angular component

Currently facing an issue with my Angular assignment where changing an element's value doesn't reflect in the browser, even though the change is logged in the console. The task involves toggling the status of a member from active to inactive and ...

You cannot access the property 'subscribe' on a void type in Angular 2

fetchNews(newsCategory : any){ this.storage.get("USER_INFO").then(result =>{ this.storage.get("sessionkey").then(tempSessionKey =>{ this.email = JSON.parse(result).email; this.newSessionKey = tempSessionKey; this.authKey =JSON.stringify("Basic ...

When a block reaches a certain height, the mat-chip-list in Angular Material is automatically shortened to fit. This feature is exclusive to

<div fxFlex="100" fxFlex.gt-sm="80" fxFlex.sm="100"> <div *ngFor="let permission of arrayOfObjectPermissions; let index = z" class="permissions-list"> <mat-card [title]=&qu ...