Angular NGXS Auth Guard: How to solve Race Condition with User State

Discussão em 'Angular' iniciado por Ilias Bgl, Março 17, 2025.

  1. Ilias Bgl

    Ilias Bgl Guest

    I’m experiencing a race condition when using an auth guard with NGXS state management in an Angular application. The guard should check if the user is authenticated and has the required roles before granting access. However, the user state is null initially, causing unwanted redirects to "/forbidden" even when the user is eventually loaded. Here’s my current implementation:

    import { inject } from '@angular/core';
    import { CanActivateFn, Router } from '@angular/router';
    import { Store } from '@ngxs/store';
    import { SecurityState } from './components/state/security.state';
    import { map } from 'rxjs';

    export const authGuard: CanActivateFn = (route, state) => {
    const roles = route.data["roles"];
    console.log("before return");
    const router = inject(Router);

    return inject(Store).select(SecurityState.getCurrentUser).pipe(
    map(user => {
    console.log(user);
    if ((!roles && user) || user?.roles?.some(userRole => roles?.includes(userRole))) {
    return true;
    }
    router.navigate(["/forbidden"]);
    return false;
    })
    );
    };

    Continue reading...

Compartilhe esta Página