What are the reasons for discouraging the use of canActivate always returning false?

I've searched extensively to avoid duplicate postings and tried various solutions, but unfortunately, none of them have resolved the issue.

My implementation of canActivate to secure a dashboard seems to be working properly, but it's always returning false, preventing me from accessing the protected routes.

There are no error messages or indications that could help me pinpoint and fix the problem. The isAuthenticated flag remains false despite calling the setAuthenticated() function to set it to true.

Any suggestions on how to address this?

auth.service.ts:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class AuthService {

    public isAuthenticated = false;

    constructor(private http: HttpClient) {
    }

    setUserLoggedIn() {
        this.isAuthenticated = true;
    }

    getUserLoggedIn() {
        return this.isAuthenticated;
    }

    public setAuthenticated() {

        this.http
            .get<any>(url, {withCredentials: true, observe: 'response'})
            .subscribe(
                (res) => {
                    console.log('Status: Authenticated: ' + res.headers.get('status') );
                    if ( res.headers.get('status') === '200') {
                        this.setUserLoggedIn();
                    }
                },
                err => {});
    }
}

authguard.guard.ts:

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


@Injectable()
export class AuthguardGuard implements CanActivate {
    constructor(
        private user: AuthService,
        public router: Router,
        private http: HttpClient,
        private activatedRoute: ActivatedRoute) {
    }

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

        if ( !this.user.isAuthenticated ) {
            console.log('Not authenticated!');
            this.router.navigate(['userLogin']);
            return false;
        }
        return true;
    }
}

Answer №1

To enhance security, utilizing Observables in Auth-Guard is highly recommended. Here's how you can achieve this:

Firstly, in auth.service.ts, modify the "setAuthenticated" method as shown below.

public setAuthenticated() {
// Ensure to set "isAuthenticated" value to FALSE once the session expires.
if (this.isAuthenticated === true) {
    return Observable.of(true);
} else {
    return this.http.get<any>(url, {withCredentials: true, observe: 'response'})
      .map((res) => {
        if ( res.status === 200) {
             this.isAuthenticated = true;
             return true;
        } else {
            this.isAuthenticated = false;
            console.log('User not authenticated!');
            this.router.navigate(['userLogin']);
            return false;
        }
    });
}
}

Next, in authguard.guard.ts file:

// All necessary imports
@Injectable()
export class AuthguardGuard implements CanActivate {
constructor(
    private user: AuthService,
    public router: Router,
    private http: HttpClient,
    private activatedRoute: ActivatedRoute) {
}

canActivate(): Observable<boolean> {
   return this.user.setAuthenticated()
     .map((res) => {
        if ( res === true) {
             return true;
        } else {
            console.log('User not authenticated!');
            this.router.navigate(['userLogin']);
            return false;
        }
    });
  }
}

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

Issue with debugging Azure Functions TypeScript using f5 functionality is unresolved

I am encountering issues running my Azure TypeScript function locally in VS code. I am receiving the errors shown in the following image. Can someone please assist me with this? https://i.stack.imgur.com/s3xxG.png ...

Converting a String into a Type or Component in Angular: A Step-by-Step Guide

Is it feasible in Angular to convert a string into a specific type or component? For instance, if I have the string "ListComponent", could I dynamically add a ListComponent to the application without using mapping techniques? stringComponent = "ListComp ...

Angular Material Table displaying real-time information

Recently, I've delved into Angular and have been experimenting with creating a dynamic table to showcase data. Currently, I have managed to get it partially working with static data. I drew inspiration from this particular example: https://stackblit ...

Displaying rows in a mat-table based on a certain condition

Is there a way to only display data in the table if the status is 'done'? I attempted to remove the status, but it still shows the row. Any suggestions on how to achieve this? data { equipmentOrdered: 'laptop', qty: 1, s ...

Tips for ensuring that npm only creates one instance of a dependency when it is being used by multiple projects

Struggling a bit here. I am diving into npm and configuration files for the first time. The current challenge involves setting up a vue project (though it might not be directly related to the issue) with typescript and then reusing its code and components. ...

Can you explain the significance of this particular line in the source code of VSCode?

While browsing through the VS Code source code, I stumbled upon the following snippet: https://github.com/microsoft/vscode/blob/5da4d93f579f3fadbaf835d79dc47d54c0d6b6b4/src/vs/workbench/contrib/comments/browser/commentsEditorContribution.ts#L166 It appear ...

Tips for making concurrent API requests in Angular 7

Can anyone help me with sending multiple requests from different pages in Angular 7 and Typescript? For example, I have a page called Email where I need to send 1000 emails one by one and update the status in a variable. This process should run in the bac ...

What is the best way to securely store a JWT Token received from Cognito after logging in through the Cognito Hosted UI?

Our current architecture involves front end Angular and backend nodejs/express. This setup functions in the following order: User logs in to the site via Cognito Hosted UI Upon successful login, the user is redirected to our home page with a code sent in ...

Struggling to navigate through rows in a Material UI Table

After performing a search in my TextField, the rows appear correctly in the console. However, the table itself does not update at all. I attempted to set the result of the search to a new array, but this made my TextField read-only. Any assistance with fur ...

Issue: Unable to locate a change supporting element '[object Object]' of the type 'object - Angular 7'

An angular service has been created for the specified purpose: CheckTicket(barcode, codEspec, diaHoraEspec):Observable<Ticket[]>{ //read ticket return this.http.get<Ticket[]>(`${this.checkticket_url}${barcode}?token=${this.token}&a ...

Creating an Angular template using the Teams Toolkit within Visual Studio Code

I'm looking to create a basic step-by-step form on Microsoft Teams using my existing Angular application. However, I've noticed that there are only React templates available in Visual Studio Code for building tabs in Teams. Do I have to use these ...

The program abruptly shut down with error code 127. Any idea why this occurred?

I'm having issues while attempting to create an app from a script. When I run "ionic serve," the following errors occur: [error] Error: Job name "..getProjectMetadata" does not exist. at Observable._subscribe (C:\Users\Bhanu\Desktop&bs ...

Discover the specifics of an element within angular version 6

My goal is to have the details of a course module displayed when it is clicked. However, I am encountering an error with my current code: Cannot read property 'id' of undefined. coursemoduleapi.service.ts getCourseModule(id:number) { return thi ...

Is there a way to turn off TypeScript Inference for imported JavaScript Modules? (Or set it to always infer type as any)

As I attempt to utilize a JS module within a TypeScript File, I encounter errors due to the absence of type declarations in the JS module. The root cause lies in a default argument within the imported JS function that TypeScript erroneously interprets as ...

When implementing JSS with React and TypeScript, certain CSS properties may encounter a `type is unassignable` error

Recently delving into TypeScript, I've encountered an issue within my project that was created using create-react-app with TypeScript and incorporates JSS. It appears that certain CSS properties are causing errors. Specifically, the pointerEvents and ...

Loop through the ng-content elements and enclose each one within its own individual nested div

Although it is currently not supported, I am curious to know if anyone has discovered a clever solution to this problem. In my current setup, I have a parent component with the following template: <dxi-item location='after' class="osii-item- ...

What is the best way to execute an Nx executor function using Node.js?

Can a customized Nx executor function be executed after the app image is built? This is the approach I am taking: "migrate-up": { "executor": "@nx-mongo-migrate/mongo-migrate:up", "options": { &q ...

execution of synchronized task does not finish

My approach to running Protractor tests in a headless mode using Xvfb may not be the most efficient, so let me outline my high-level requirement first. I am utilizing the angular2-seed and I aim to execute Protractor tests in a headless mode by incorporat ...

What is the method for retrieving the index of an enum member in Typescript, rather than the member name?

Here is an example of how to work with enums in TypeScript: export enum Category { Action = 1, Option = 2, RealEstateFund = 3, FuturesContract = 4, ETFs = 5, BDRs = 6 } The following function can be used to retrieve the enum indexe ...

I encountered an issue where I did not receive a response when utilizing res.write() within the fetch function

Currently, I am utilizing the <res.write()> method in nodejs at https://nodejs.org/api/http.html#responsewritechunk-encoding-callback. In addition to this, I am also implementing the fetch function which can be found at https://developer.mozilla.org/ ...