Angular 刷新页面时触发应用丢失授权状态

Angular fire app losing authstate upon refreshing the page

大家好我正在使用 angular 和 firebase 开发一个共享应用程序,我遇到了一个问题 1. 以前从未遇到过 2. 尝试过堆栈溢出的解决方案无济于事。我正在我的应用程序中实施身份验证保护,以便某些页面只能由经过身份验证的用户查看。 这是我的登录指令代码:

import { Directive, HostListener } from '@angular/core';
import { AngularFireAuth } from '@angular/fire/auth';
import * as firebase from 'firebase/app';

@Directive({
  selector: '[appGoogleSignin]',
})
export class GoogleSigninDirective {
  constructor(private afAuth: AngularFireAuth) {}

  @HostListener('click')
  onclick() {
    this.afAuth
      .setPersistence(firebase.default.auth.Auth.Persistence.LOCAL)
      .then(() => {
        this.afAuth.signInWithPopup(
          new firebase.default.auth.GoogleAuthProvider()
        );
      });
  }
}

这是我的授权代码:

import { Injectable } from '@angular/core';
import { AngularFireAuth } from '@angular/fire/auth';
import {
  CanActivate,
  ActivatedRouteSnapshot,
  RouterStateSnapshot,
  UrlTree,
} from '@angular/router';
import { Observable } from 'rxjs';
import { SnackService } from '../services/snack.service';

@Injectable({
  providedIn: 'root',
})
export class AuthGuard implements CanActivate {
  constructor(private afAuth: AngularFireAuth, private snack: SnackService) {}

  async canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Promise<boolean> {
    const user = await this.afAuth.currentUser;
    const isLoggedIn = !!user;
    if (!isLoggedIn) {
      this.snack.authError();
    }

    return isLoggedIn;
  }
}

下面是我对 auth guard 的实现:

    path: 'upload',
    loadChildren: () =>
      import('./upload/upload.module').then((m) => m.UploadModule),
    canActivate: [AuthGuard],
  },

我已经尝试过多种解决堆栈溢出的方法,包括将持久化状态设置为会话和本地。 None 对我有用。

this.afAuth.currentUser 值在您加载页面时异步刷新。因此,当您的代码访问 this.afAuth.currentUser 时,它可能尚未设置。

不要同步访问 this.afAuth.currentUser 值,而是观察 auth.user 流以确保您始终对最新的身份验证状态做出反应。另请参阅 Getting started with Firebase Authentication.

中的第一个代码示例