簡體   English   中英

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

[英]Angular AuthGuard CanActivate not called when signing out - Firebase Auth

登錄后正確調用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))
    );
  }
}

驗證服務

  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會觸發

我認為您應該從以下內容中刪除take(1)

return this.angularFireAuth.authState.pipe(
    take(1),
    map(authState => !!authState)
);  

使用take(1)時(登錄時您只能接收到來自observable的數據。

我看不到您在AppModule providers數組中添加了防護,這可能會解決您的問題。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM