禁用 Firebase 身份验证状态持久性

时间:2021-04-30 17:46:42

标签: javascript node.js firebase google-cloud-firestore

我目前有这个登录功能:

AuthorizationHome.doSignInWithEmailAndPassword(email, password)
    .then(() => {
      firebase.auth().onAuthStateChanged((user) => {
                ..........

但它基本上可以让我的会话保持登录状态,即使我关闭浏览器、重新启动计算机,它也能完成所有工作。因为用户可以通过我的应用管理他们的付款,所以我需要确保如果他们关闭浏览器,它会将他们注销。

Firebase 文档告诉我这样做:

    firebase.auth().setPersistence(firebase.auth.Auth.Persistence.SESSION)
  .then(() => {
    return firebase.auth().signInWithEmailAndPassword(email, password);
  })
  .catch((error) => {
    // Handle Errors here.
    var errorCode = error.code;
    var errorMessage = error.message;
  });

它与我的原始代码不同,所以我不知道该怎么做。我对 firebase 的工作方式完全陌生,所以我有点困惑。

1 个答案:

答案 0 :(得分:1)

您是否尝试在 firebase.auth().onAuthStateChanged 成功解析后执行 AuthorizationHome.doSignInWithEmailAndPassword(email, password)

firebase
  .auth()
  .setPersistence(firebase.auth.Auth.Persistence.SESSION)
  .then(() => {
    return AuthorizationHome.signInWithEmailAndPassword(email, password).then(() => {
      firebase.auth().onAuthStateChanged((user) => { /* do things */ });
    });
  })
  .catch((error) => {
    // Handle Errors here.
    const errorCode = error.code;
    const errorMessage = error.message;
  });

话虽如此,您可能可以单独运行 setPersistence(firebase.auth.Auth.Persistence.SESSION) 作为应用初始化的一部分。它不必在每次执行 doSignInWithEmailAndPassword 之前运行:

// app initialization
firebase
  .auth()
  .setPersistence(firebase.auth.Auth.Persistence.SESSION)

// somewhere else on demand
AuthorizationHome.doSignInWithEmailAndPassword(email, password)
    .then(() => {
      firebase.auth().onAuthStateChanged((user) => {

希望有帮助!