Why is the authentication service failing to remember user authentication?

Despite having an auth guard and auth service that are functioning correctly, I encounter the issue of being logged out when attempting to access my application in a new browser tab. Each time a new tab is opened, I am prompted to log in again. Ideally, the auth service should remember my login status as long as the application is running without the need for repeated authentication. How can this behavior be modified to maintain my logged-in state across multiple tabs?

@Injectable()
export class AuthService {

  private loggedIn = false;

  get isLoggedIn() {
    return this.loggedIn;
  }

  constructor(private router: Router) {
  }

  login(user: User) {
    this.loggedIn = true;
    window.localStorage.setItem('user', JSON.stringify(user));
    this.router.navigate(['/vds-list']);
  }

  logout() {
    this.loggedIn = false;
    window.localStorage.clear();
    this.router.navigate(['/login']);
  }
}

@Injectable()
export class AuthGuard implements CanActivate, CanActivateChild {

  constructor(private authService: AuthService, private router: Router) {
  }

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

  canActivateChild(childRoute: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    return this.canActivate(childRoute, state);
  }
}

The issue arises from the fact that despite having a loggedIn variable and an isLoggedIn method that should return true after successful authentication once, it only works within the same tab. This discrepancy leads to AuthService#loggedIn returning false even though I am authenticated.

Answer №1

Before anything else, make sure to retrieve the user data from localStorage when opening new tabs or refreshing the page.

Consider including this code snippet in the constructor of your AuthService:

try {
  let userJson = window.localStorage.getItem('user');
  let user = JSON.parse(userJson);
  this.isLoggedIn = !!user;
} catch (e) {
  // no user found
}

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

When working on styling a different Styled Component, how should one define the type of props required?

I'm currently working on a NextJS project using styled components and typescript. I have customized a div element like this: export const ClippedOverlay = styled( ( props: React.DetailedHTMLProps< React.HTMLAttributes<HTMLDivElement& ...

The Bootstrap modal I implemented is opening correctly, but for some reason, the form inside is not appearing

I created the AddJokeModalComponent to streamline the process of opening a form without duplicating code in every component. Below is the modal structure: <ng-template #addJokeModal> <div class="modal-content my-custom-modal"> ...

I have a Visual Studio 2019 solution that consists of two projects - one is an Angular project and the other is written in TypeScript. I have successfully configured

We are currently utilizing Visual Studio 2019 (not the VS Code version) for our project. Within this solution, we have multiple projects included. One of these projects contains Angular code that we compile using the traditional 'ng build' comma ...

How can I target the initial last element within an *ngFor loop?

In my current project using Ionic, I am developing a personal application where I aim to implement an alphabetical header/divider for a list of games. The idea is to check the first letter of each game, and whenever it differs from the last game's ini ...

Do interfaces in Typescript require nested properties to be mandatory?

My interface contains a nested object: export interface Person { PersonWrapper: { name: string; address: string email?: string; } } When attempting to create an object from this interface, it appears that name is not mandat ...

What is the best method for incorporating an Angular Component within a CSS grid layout?

I recently started learning Angular and am currently working on a project that requires the use of a CSS grid layout. However, I'm facing an issue with inserting a component inside a grid area specified by grid-area. My attempt to achieve this in app ...

Retrieve information from a URL to transmit to a different page in NextJS using Typescript and AppRouter

I'm struggling with transitioning from the Home page to the Detail page. I've successfully passed data to the URL from the Home screen, but I'm having trouble accessing it in the Detail screen. I'm working with NextJS ver 13, using Type ...

Exploring the detection of changes in variables using Aurelia

Is it possible to track changes to a variable using aurelia? While I know that I can detect changes in a variable's type using @observable, I am curious if it is possible to monitor changes in a variable's value, for example from a = 3 to a = 4, ...

To achieve this, my goal is to have the reels start playing on a separate page when a user clicks on the designated image. I am currently working on a project that involves this

When a user clicks on the designated image, I want the reels to start playing on a separate page. In my main project, I have a reels project within it, with the reels project built in ReactJS and the main project in React TypeScript. For example, if a user ...

The index type in TypeScript's keyof function is overly broad

Sorry if this question has been addressed before, but I'm having trouble finding the right search terms. Feel free to correct my question if necessary. This is what I have: type RowData = Record<string, unknown> & {id: string}; type Column&l ...

What is the best way to define the entry points for all files in tsup/typescript that compile into the root dist

In my TypeScript project, I am utilizing the tsup build tool for bundling. I have a requirement to specify all the folders and files within the components directory to the root dist folder. src/ components/ card/ card.tsx ...

What is the method for accessing an anonymous function within a JavaScript Object?

Currently facing an issue with a Node.js package called Telegraf, which is a bot framework. The problem arises when trying to create typings for it in TypeScript. The package exports the following: module.exports = Object.assign(Telegraf, { Composer, ...

Retrieve the attributes of a class beyond the mqtt callback limitation

Currently, I am utilizing npm-mqtt to retrieve information from a different mqtt broker. My objective is to add the obtained data to the array property of a specific class/component every time a message is received. However, I'm facing an issue wher ...

Exploring subclasses in TypeScript

When working with TypeScript and defining an interface like the one below: export interface IMyInterface { category: "Primary" | "Secondary" | "Tertiary", } Can we access the specific "sub types" of the category, such as ...

Strategies for managing the "ref" property of Material-UI component props within our custom components

I have a unique custom component setup as shown below: // ... import { PaperProps, styled } from '@mui/material'; type ComponentProps = PaperProps & { a: string, b: string }; export const MyPaper = styled(Paper)(/* ... */); const Compo ...

Issue with npm resolution due to package requiring another third-party dependency

I'm encountering an issue with a requirement and I'm hoping for some assistance. I currently have a package called @unicoderns/orm that relies on mysql, which can be found at https://github.com/unicoderns/ORM Now I'm working on developing ...

Chess.js TypeScript declaration file for easy implementation

Currently, I am delving into learning typescript and have taken up the challenge of crafting a declaration file for the chess.js library. However, it seems that I am struggling to grasp the concept of creating one. Whenever I attempt to import the library ...

Tips for creating test cases for the following Angular method

Looking for advice on creating Jasmine unit test cases for a method that opens a custom type dialog in my component. export class OpenPopUpComponent implements OnInit { constructor(public dialog:NewCustomDialog) {} ngOnInit() { } open ...

Monitoring a Typescript Class's Get() or Set() function using Jasmine Spy

While working with Jasmine 2.9, I have encountered no issues spying on both public and private functions, except for when trying to spy on a get or set function at the class level. private class RandomService { public dogsHealth = 0; private get pers ...

Pressing the confirm button will close the sweet alert dialog

When pressing the confirm button, the swal closes. Is this the intended behavior? If so, how can I incorporate the loading example from the examples? Here is my swal code: <swal #saveSwal title="Are you sure?" text ="Do you want to save changes" cancel ...