Angular auth guard async/subscription problems

Discussão em 'Angular' iniciado por sirzento, Março 3, 2025.

  1. sirzento

    sirzento Guest

    I am using an auth guard to protect my routes. The problem I have is that if I want to access the homepage, I get redirected to the login from the auth guard. After I press login, I will get redirect to the return url and auth guard gets called again. Thats no problem but in this call, the user is still not set so I will stay at the login page. Pressing login a second time will fix this and redicrect me correctly.

    Why is my user value still not set here?

    auth.guard.ts:

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    const user = this.authenticationService.userValue;
    if (user) {
    return true;
    } else {
    this.router.navigate(['/login'], { queryParams: { returnUrl: state.url } });
    return false;
    }
    }


    auth.service.ts:

    private userSubject: BehaviorSubject<User | null>;

    public get userValue() {
    return this.userSubject.value;
    }

    login(username: string, password: string) {
    return this.http.post<any>(`${environment().apiUrl}/auth/login`, { username, password }, { withCredentials: true })
    .pipe(map(async (user) => {
    user.permissions = await this.getUserPermissions(user);
    this.userSubject.next(user);
    this.startRefreshTokenTimer();

    return user;
    }));
    }


    login.component.ts:

    onSubmit(data: {username: string, password: string}) {
    this.authService.login(data.username, data.password).pipe(first()).subscribe({
    next: () => {
    const returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/';

    this.router.navigate([returnUrl]);
    },
    error: (err) => {
    console.error(err);
    },
    })
    }

    Continue reading...

Compartilhe esta Página