Issue with Angular 17 custom guard failing to function properly when used alongside a backend axios request

I am in the process of developing an Angular application that includes a protected page. To secure this page, I have implemented a custom guard:

{
  path       : 'intern', // For testing purposes (internal page)
  component  : InternalComponent,
  canActivate: [loggedInGuard],
}

The code for my login guard is as follows:

export const loggedInGuard: CanActivateFn = (route, state): Promise<boolean> => {
  const loginService = inject(LoginService);
  const router       = inject(Router);

  return new Promise((resolve, reject) => {
    loginService.isLoggedIn().then((isLoggedIn) => {
      if (!isLoggedIn) {
        router.navigate(['/login'], {queryParams: {redirect_to: state.url}}).then(() => {
          resolve(false);
        });
      } else {
        resolve(true);
      }
    });
  });
};

Within the guard, it is essential to check if the user is logged in using the service provided:

public async isLoggedIn(): Promise<boolean> {
  const token = localStorage.getItem(this.tokenKey);
  if (!token) {
    return false;
  }
  try {
    // await axios.post(this.verifyLoginUri, {token});
    return true;
  } catch (error) {
    this.logout();
    return false;
  }
}

Initially, a check is made to ensure that the token received during login is still saved in local storage. If present, the token is used to make a backend request utilizing axios to confirm its existence within the Redis DB. In case the token cannot be found, a 401 error is returned and handled by the catch block. If the token does exist in the database, a 200 response is sent back.

However, it seems that the guard is not processing the backend request correctly. When the axios request is enabled, the protected page displays no content. On the other hand, when the request is disabled, the content on the page appears based on the local storage data.

I am puzzled about what mistake I might be making. This scenario aligns with common security practices where every service validates sessions in the backend to prevent unauthorized access through manipulation of local storage data.

Answer №1

Consider transforming the commitment into an observable.

public verifyAuthentication(): any {
  const userToken = localStorage.getItem(this.tokenKey);
  if (!userToken) {
    return false;
  }
  try {
    return from(axios.post(this.checkAuthUri, {token: userToken})).pipe(
        map((response:any)=> {
           return true;
        })
    );
  } catch (error) {
    this.signOut();
    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

What is the proper way to indicate the pointer to the current element within the array?

How can I modify a code that displays a list of posts? import React from "react"; type respX = { "id": any, "userId": any, "title": any, "body": any, } interface PropsI { } interface StateI { data: respX []; } export class Compone ...

Finding the attribute value within a nested array of objects retrieved from an API response

Imagine a scenario where I possess an array of unclassified objects, each of which contains an array of labeled objects: [{id: 123, name: 'Foo', code: 'ABC123', enabled: true},{id: 124, name: 'Bar', code: '123ABC', e ...

Error message in React: "The type 'Window & typeof globalThis' does not have a property named 'ethereum'"

Encountering a problem: Issue with 'ethereum' property on type 'Window & typeof globalThis' In my React project, I'm facing an error. The following code is causing the problem: import { ethers } from 'ethers' cons ...

The CORS policy has blocked access to XMLHttpRequest because the 'Access-Control-Allow-Origin' header is missing on the requested resource

I encountered an issue where making a call from my Angular 7 application to my ASP.NET Web API resulted in an exception. When attempting to send an HTTP post request from Angular to an application running on a different port, a CORS policy error was thrown ...

The ASP .Net Core 3.1 Angular template is malfunctioning

https://i.sstatic.net/T3hFx.pngAfter creating a new Web Project using the .Net Core with Angular template in Visual Studio 2019, I encountered an error when trying to build the solution. The error message stated: An unhandled exception occurred while proce ...

The table __EFMigrationsHistory does not exist

Trying to navigate the world of .NET Core and facing some challenges. When I enter the following command in the VS Code terminal dotnet ef database update I encounter the following message: Build started... Build succeeded. info: Microsoft.EntityFramework ...

Angular 2 Mouseover Functionality

Can anyone share the correct method for creating a hover-like event in the latest Angular2 framework? In the previous Angular1 version, we used ng-Mouseover for this purpose, but it seems like it is no longer available in Angular2. I have searched throug ...

Issues arise when attempting to utilize Async/Await with a gRPC method

Here is the code snippet used to initialize a gRPC server: export const initServer = async (finalPort: number): Promise<string> => { let initStatus = 'initial'; gRPCserver.addService(webcomponentHandler.service, webcomponentHandler.h ...

Using an additional router-outlet in an Angular 2 application: a step-by-step guide

I have been facing an issue with my angular2 app where I am attempting to use 2 router-outlets. Despite reading numerous blogs and conducting multiple Google searches, I have not been able to make it work. I would greatly appreciate any suggestions on why ...

Tips for Modifying the currentUrl identifier in Angular 2

I am trying to change the ID property of my currentUrl object within my component. My goal is for the ID to update and then fetch the corresponding data based on that ID. However, I keep encountering this error message: "Cannot assign to read only propert ...

Conceal certain components when a user is authenticated

Below is the content of my app.component.html: <nav class="navbar navbar-expand-lg navbar-light bg-light"> <div class='container'> <ul class="nav navbar-nav"> <li class='nav-item'> <a clas ...

Unit testing the TypeScript function with Karma, which takes NgForm as a parameter

As I work on writing unit tests for a specific method, I encounter the following code: public addCred:boolean=true; public credName:any; public addMachineCredential(credentialForm: NgForm) { this.addCred = true; this.credName = credentialForm.val ...

Mastering the art of integrating PrismJS and its typings effectively in TypeScript and Angular 2

I'm putting together a small application using angular-cli and I am trying to integrate PrismJS but facing issues with making it function properly. Essentially, I've set up a vendor directory where I have placed Prism's scripts and styles, ...

Battle of the Blobs: Exploring Blob Source in Google Apps Script

I've been exploring clasp, a tool that allows developers to work with Google Apps Script using TypeScript. Currently, I am working on a script that converts a Google Sheet into a PDF Blob and then uploads it to Google Drive. While the code is execut ...

Encountering a CORS error after deploying an Angular and Spring Boot application on Heroku

Currently facing challenges with an app due to CORS issues. It functions perfectly locally, but once deployed, an error occurs. Access to XMLHttpRequest at 'https://portafolioback.herokuapp.com/portafolio/version1/post/all' from the origin &apos ...

Change a numeric value into a string within a collection of objects

Consider the following input array: const initialArray = [ { id: 1, name: 1 }, { id: 2, name: 2 }, { id: 3, name: 3 }, { id: 4, name: 4 } ]; The objective is to modify it ...

Definition file in TypeScript for an npm package provided by an external source - constructor

In my Node project, I am utilizing ES6 and Typescript. Despite this, there is a commonjs library that I need to incorporate. To address this, I have created my own .d.ts declaration file for the library: module "@alpacahq/alpaca-trade-api" { e ...

How should I format my JSON data to track monthly attendance?

Do you have a material table that needs to be filled day by day? Here's how you can do it: Check out the image example! I've set up a JSON server with data structured like this: { "posts": [ { "empid": 12345, "name": "Dharini I ...

Unfortunately, despite attempting to kill all processes linked to port 4200, it seems that it is still in use

Getting angular up and running on my Mac OS X 10.11.3 El Capitan has been quite a challenge. After installing nodeJS and npm, I used npm to install angular-cli. To create a new app, I executed the command sudo ng new first-app Then, I navigated into the ...

efficiently managing errors in a Nest Jest microservice with RabbitMQ

https://i.sstatic.net/sUGm1.png There seems to be an issue with this microservice, If I throw an exception in the users Service, it should be returned back to the gateway and then to the client However, this is not happening! The client only sees the de ...