如何使用 Firebase 持久性在页面刷新后保持用户登录

时间:2021-04-18 14:16:26

标签: reactjs firebase authentication firebase-authentication

我使用上下文 api 来管理用户登录状态。我还使用了 firebase auth 持久性来让用户在页面重新加载后保持登录状态,但它不起作用:/在我的会话存储中,用户信息正在被保存,但之后页面重载用户会自动退出应用程序。

登录上下文.js

export const LoginContext = createContext();
const LoginContextProvider = ({ children }) => {
  const [loggedInUser, setLoggedInUser] = useState({});
  return (
    <LoginContext.Provider value={[loggedInUser, setLoggedInUser]}>
      {children}
    </LoginContext.Provider>
  );
};

登录.js

const gmailProvider = new firebase.auth.GoogleAuthProvider();

  const handleGmailSignIn = () => {
    firebase
      .auth()
      .setPersistence(firebase.auth.Auth.Persistence.SESSION)
      .then(() => {
        firebase
          .auth()
          .signInWithPopup(gmailProvider)
          .then((result) => {
            const { displayName, email, photoURL } = result.user;
            const signedInUser = {
              isSignedIn: true,
              name: displayName,
              email: email,
              photoURL: photoURL,
            };
            // setUserToken();
            setLoggedInUser(signedInUser);
            history.replace(from);
            console.log(displayName, email);
          });
      })

      .catch((error) => {
        // Handle Errors here.
        const errorCode = error.code;
        const errorMessage = error.message;
        // The email of the user's account used.
        const email = error.email;
        // The firebase.auth.AuthCredential type that was used.
        const credential = error.credential;
        // ...
      });
  };

1 个答案:

答案 0 :(得分:1)

在页面刷新时,Firebase 身份验证必须从缓存中加载身份验证凭据并重新验证它们。这是一个异步过程,可能需要几秒钟的时间,导致“用户未登录”状态。

监听 auth 状态变化很重要

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    // User is signed in.
  } else {
    // No user is signed in.
  }
});

来源:https://firebase.google.com/docs/auth/web/manage-users#get_the_currently_signed-in_user

有很多教程以几种不同的方式实现这一点,您可以在这里找到一些: https://johnwcassidy.medium.com/firebase-authentication-hooks-and-context-d0e47395f402 https://stackoverflow.com/a/50204490/2301161