beachCode
beachCode

Reputation: 3530

Angular 6 auth guard stays on blank page when logged in

I found this answer and I'm modifying it work with my authentication: Angular 6 AuthGuard

However, when the user is successfully authenticated, the auth guard just goes to a blank page instead of forwarding to the URL. Note that it works as expected when the user has no token. It forwards to the login page.

I see the console output for the "valid token" line, but the redirect doesn't happen. Also, if I put "return true;" at the top of the handler, the forwarding works.

Here's the code block in question from my auth guard service:

authenticationHandler(): boolean {
    if (this.myToken) {
      this._auth.validateToken(this.myToken)
        .subscribe((result) => {
          if (result.value) {
            // TODO
            console.log('AuthGuard: valid token');

            this.loggedIn.next(true);
            return true;
          } else {
            this.loggedIn.next(false);
            this._router.navigate(['/login']);
            return false;
          }

        });
    } else {
      this.loggedIn.next(false);
      this._router.navigate(['/login']);
      return false;
    }
  }

  canActivate(): boolean {
    return this.authenticationHandler();
  }

Upvotes: 0

Views: 1030

Answers (1)

EmandM
EmandM

Reputation: 960

You are returning true inside the subscribe function, that value doesn't get passed further out to the route guard. Instead the route guard is returning undefined which evaluates to falsey.

You want the route guard to wait for the token to validate before returning. The simplest way of achieving this is using async/await syntax.

async authenticationHandler(): Promise<boolean> {
  if (this.myToken) {
    const result = await this._auth.validateToken(this.myToken).toPromise();
    if (result.value) {
        // TODO
        console.log('AuthGuard: valid token');

        this.loggedIn.next(true);
        return true;
     } else {
        this.loggedIn.next(false);
        this._router.navigate(['/login']);
        return false;
     }

  } else {
    this.loggedIn.next(false);
    this._router.navigate(['/login']);
    return false;
  }
}

This way your code will have the validation result before returning out of the route guard.

Upvotes: 1

Related Questions