首页 > 解决方案 > firebaseAuth.onAuthStateChanged 返回用户 null

问题描述

我正在尝试使用 firebase auth 来实现身份验证,事情是当涉及到持久性时,我被卡住了。我尝试使用本地存储,如下所示:

AuthService.ts :

import {HttpClient} from '@angular/common/http';
import { Injectable } from '@angular/core';
import {AngularFireAuth} from '@angular/fire/auth';
import {Router} from '@angular/router';
import firebase from 'firebase/app';

@Injectable({
  providedIn: 'root'
})

export class AuthService {

  userData: any;

  constructor(private http: HttpClient, private firebaseAuth: AngularFireAuth, private router: Router) {
    this.firebaseAuth.useEmulator('http://localhost:9099');
    this.firebaseAuth.authState.subscribe(user => {
      if (user) {
        this.userData = user;
        localStorage.setItem('user', JSON.stringify(this.userData));
        JSON.parse(localStorage.getItem('user'));
      } else {
        localStorage.setItem('user', null);
        JSON.parse(localStorage.getItem('user'));
      }
    });
    this.firebaseAuth.onAuthStateChanged( user => {
      console.log(user);
    });
  }



  signIn(email: string, password: string): void {
    this.firebaseAuth.setPersistence(firebase.auth.Auth.Persistence.LOCAL).then(() => {
      this.firebaseAuth.signInWithEmailAndPassword(email, password)
        .then(result => {
          this.router.navigate(['/dashboard/accueil']);
          console.log('Nice, it worked!');
        })
        .catch(error => {
          console.log('Something went wrong:', error.message);
        });
    }).catch(error => {
      console.log('Something went wrong:', error.message);
    });
  }

  signOut(): void {
    this.firebaseAuth.signOut().then(() => {
      localStorage.removeItem('user');
      this.router.navigate(['/dashboard/connexion']);
    });
  }

  forgetPassword(email: string): void {
    this.firebaseAuth.sendPasswordResetEmail(email).then(() => {
      window.alert('Password reset email sent, check your inbox.');
    }).catch((error) => {
      window.alert(error);
    });
  }

  get isLoggedIn(): boolean {
    const user = JSON.parse(localStorage.getItem('user'));
    return (user !== null) ? true : false;
  }


}

但问题是firebaseAuth.onAuthStateChanged在用F5甚至authState刷新页面后返回null。就像 onAuthStateChange 在刷新后失去了他的最后一个状态。

请注意,我正在使用 firebase 模拟器。

app.module.ts Firebase 模块已经很好导入

AngularFireModule.initializeApp(environment.firebase),
AngularFireAuthModule,

您可以在这里查看配置: environnement.ts

 firebase: {
    apiKey: 'xxxxxxxxxxxx',
    projectId: 'xxxx'
  }

也许这是我在刷新页面时在 Web 控制台中遇到的此错误的链接:

发布https://www.googleapis.com/identitytoolkit/v3/relyingparty/getAccountInfo?key=xxxxxxx 400

请注意,密钥等于我在配置中的 apiKey 状态。

当我在这里仔细观察时,错误说明了什么:

{
  "error": {
    "code": 400,
    "message": "INVALID_ID_TOKEN",
    "errors": [
      {
        "message": "INVALID_ID_TOKEN",
        "domain": "global",
        "reason": "invalid"
      }
    ]
  }
}

任何帮助将不胜感激。

编辑

从 onAuthStateChanged 刷新我的页面后,我得到了什么: 在此处输入图像描述

没有 2 个调用,只有 1 个返回 false。

标签: javascriptangularfirebasefirebase-authentication

解决方案


默认情况下,Firebase Auth 将保持登录状态,因此您不必手动将令牌保存到本地存储中。正如弗兰克所说,onAuthStateChanged 将触发用户最初为 null,但如果用户已登录,它将在不久之后以实际用户值再次触发。


推荐阅读