Angular2 auth guard with http request and observables

Tim picture Tim · Aug 20, 2016 · Viewed 6.9k times · Source

i am currently implementing an angular2 example application with spring boot as backend. I am having some problems with the frontend auth guard mechanism and observables.

I am trying to achieve:

  1. when someone enters a protected route the auth guard should check if a user is already set in the auth service variable
  2. if it is not set then a http request should be issued to check if a session is available
  3. the service method should return a true/false value (asynchronously because of the possible http request)
  4. if service returns false the auth guard should redirect to login page
  5. auth guard should return true/false so the route can either be activated or not

My code currently looks like this (i am using RC5 btw.):

Auth Guard

import {Injectable} from "@angular/core";
import {CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router} from "@angular/router";
import {Observable, Subject} from "rxjs/Rx";
import {AuthService} from "./auth.service";

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private authService: AuthService, private router: Router) {}

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean {
    var authenticated = this.authService.isAuthenticated();
    var subject = new Subject<boolean>();
    authenticated.subscribe(
        (res) => {
          console.log("onNext guard: "+res);
          if(!res && state.url !== '/signin') {
            console.log("redirecting to signin")
            this.router.navigate(['/signin']);
          }
          subject.next(res);
        });
    return subject.asObservable();
  }
}

Auth Service

import {Injectable} from "@angular/core";
import {User} from "./user.interface";
import {Router} from "@angular/router";
import {Http, Response, Headers} from "@angular/http";
import {environment} from "../environments/environment";
import {Observable, Observer, Subject} from "rxjs/Rx";

@Injectable()
export class AuthService {
  private authenticatedUser : User;
  constructor(private router: Router, private http: Http) {}

  signupUser(user: User) {
  }


  logout() {
    //do logout stuff
    this.router.navigate(['/signin']);
  }

  isAuthenticated() : Observable<boolean> {
    var subject = new Subject<boolean>();
    if (this.authenticatedUser) {
      subject.next(true);
    } else {
      this.http.get(environment.baseUrl + '/user')
        .map((res : Response) => res.json())
        .subscribe(res => {
          console.log("next: returning true");
          this.authenticatedUser = User.ofJson(res);
          subject.next(true);
        }, (res) => {
          console.log("next: returning false");
          subject.next(false);
        });
    }
    return subject.asObservable();
  }
}

The problem is: the guard never allows the router component to activate, even though when i am logged in.

Thanks for the help!

Answer

G&#252;nter Z&#246;chbauer picture Günter Zöchbauer · Aug 20, 2016

Change

return subject.asObservable();

to

return subject.asObservable().first();

The router waits for the observable to complete. first() makes it complete after the first event.