登出时未呼叫Angular AuthGuard CanActivate-Firebase Auth

时间:2018-12-02 04:19:54

标签: angular firebase firebase-authentication google-cloud-firestore

登录后正确调用AuthGuard CanActivate,并将用户重定向到他们来自的路由。该问题仅在用户退出时出现,CanActivate似乎没有被触发

AuthGuard

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {
  constructor(private authService: AuthService, private router: Router) {}
  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean> {
    return this.checkLogin(state.url);
  }

  checkLogin(url: string): Observable<boolean> {
    // Store the attempted URL for redirecting
    this.authService.redirectUrl = url;
    return this.authService.isAuthenticated.pipe(
      tap(auth => (!auth ? this.router.navigate(['login']) : true))
    );
  }
}

AuthService

  get isAuthenticated(): Observable<boolean> {
    return this.angularFireAuth.authState.pipe(
      take(1),
      map(authState => !!authState)
    );
  }

应用路线

export const AppRoutes: Routes = [
  { path: "", redirectTo: "dashboard", pathMatch: "full" },
  { path: "login", component: LoginComponent },
  {
    path: "dashboard",
    component: DashboardComponent,
    canActivate: [AuthGuard]
  },
  { path: "trades", component: TradeComponent, canActivate: [AuthGuard] },
  { path: "profile", component: ProfileComponent, canActivate: [AuthGuard] }
];

@NgModule({
  imports: [RouterModule.forRoot(AppRoutes)],
  exports: [RouterModule]
})
export class AppRoutingModule {}

将that.router.navigate(['login'])添加到logout()可以,但是由于未触发AuthGuard,感觉就像是被黑客入侵了。

  logout(): void {
    var that = this;
    this.angularFireAuth.auth.signOut().then(function() {
      localStorage.clear();
      that.router.navigate(['login']);
    });
  }

我能想到的一件事是this.angularFireAuth.authState在注销时不会更改,因此不会触发AuthGuard。这意味着如果我有isAuthenticated()返回一个简单的布尔值,该布尔值在注销时设置为false,则AuthGuard会触发

2 个答案:

答案 0 :(得分:0)

我认为您应该从以下位置删除 take(1)

html { height: 115% }

使用 take(1),您将仅从一次可观察到的数据(登录时)接收数据。

答案 1 :(得分:0)

我看不到您在AppModule的providers数组中添加了防护,这可以解决您的问题。

@NgModule({
  imports: [
    RouterModule.forRoot([
      {
        path: 'dashboard', 
        component: DashboardComponent,
        canActivate:[AuthGuard],
      }
    ])
  ],
  providers: [AuthGuard]
})
class AppModule {}