Firebase身份验证在使用onAuthStateChanged时仍然不是持久的。

huangapple go评论60阅读模式
英文:

Firebase authentication is not persistent even when using onAuthStateChanged

问题

我正在使用React Native和Expo CLI以及Redux Toolkit创建一个应用程序,以下是我的RTK登录突变:

export const loginWithEmail = (builder: Builder) =>
  builder.mutation<Payload | unknown | undefined, Params>({
    queryFn: async ({ email, password }) => {
      try {
        const { user } = await signInWithEmailAndPassword(
          auth,
          email,
          password
        );

        return {
          data: {
            uid: user.uid,
            email: user.email,
            emailVerified: user.emailVerified,
          },
        };
      } catch (error) {
        const authError = error as AuthError;
        return {
          error: { ...authError },
        };
      }
    },
  });

成功登录后,身份验证状态不会保持。每当我刷新我的应用程序时,onAuthStateChanged回调返回null用户。

onAuthStateChanged(auth, (user) => {
  console.log("current-user: ", user); // 在刷新应用程序时为null

  if (user) {
    dispatch(setUser({ currentUser: user }));
  }
});

这是我的firebaseConfig:

import {
  FIREBASE_API_KEY,
  FIREBASE_AUTH_DOMAIN,
  FIREBASE_PROJECT_ID,
  FIREBASE_STORAGE_BUCKET,
  FIREBASE_MESSAGING_SENDER_ID,
  FIREBASE_APP_ID,
  FIREBASE_MEASUREMENT_ID,
} from "@env";

const firebaseConfig = {
  apiKey: FIREBASE_API_KEY,
  authDomain: FIREBASE_AUTH_DOMAIN,
  projectId: FIREBASE_PROJECT_ID,
  storageBucket: FIREBASE_STORAGE_BUCKET,
  messagingSenderId: FIREBASE_MESSAGING_SENDER_ID,
  appId: FIREBASE_APP_ID,
  measurementId: FIREBASE_MEASUREMENT_ID,
};

// 初始化Firebase
const app = getApps().length < 1 ? initializeApp(firebaseConfig) : getApp();
const analytics = getAnalytics(app);
const db = getFirestore(app);
const auth = getAuth(app);

关于包,它们也很标准,没有特殊之处:

"firebase": "9.15.0",
"react-native",
"expo",
"rtk"

更新:
在检查JS调试器后,登录后它不会创建cookie、会话存储甚至indexedDB。因此,我认为这就是用户身份验证不持久的原因,您有没有办法修复这个问题?我相当确定在登录我的React Native应用程序后,它至少应该生成一个会话或cookie。

英文:

I'm creating an app using react native w/ expo cli and redux toolkit, here is my rtk mutation for login:

export const loginWithEmail = (builder: Builder) =&gt;
  builder.mutation&lt;Payload | unknown | undefined, Params&gt;({
    queryFn: async ({ email, password }) =&gt; {
      try {
        const { user } = await signInWithEmailAndPassword(
          auth,
          email,
          password
        );

        return {
          data: {
            uid: user.uid,
            email: user.email,
            emailVerified: user.emailVerified,
          },
        };
      } catch (error) {
        const authError = error as AuthError;
        return {
          error: { ...authError },
        };
      }
    },
  });

after successfully logging in the authentication state does not persist. Whenever I refresh my app, the onAuthStateChanged callback returns the user as null.

  onAuthStateChanged(auth, (user) =&gt; {
    console.log(&quot;current-user: &quot;, user); // null when I refresh the app

    if (user) {
      dispatch(setUser({ currentUser: user }));
    }
  });

Here is my firebaseConfig:

import {
  FIREBASE_API_KEY,
  FIREBASE_AUTH_DOMAIN,
  FIREBASE_PROJECT_ID,
  FIREBASE_STORAGE_BUCKET,
  FIREBASE_MESSAGING_SENDER_ID,
  FIREBASE_APP_ID,
  FIREBASE_MEASUREMENT_ID,
} from &quot;@env&quot;;

const firebaseConfig = {
  apiKey: FIREBASE_API_KEY,
  authDomain: FIREBASE_AUTH_DOMAIN,
  projectId: FIREBASE_PROJECT_ID,
  storageBucket: FIREBASE_STORAGE_BUCKET,
  messagingSenderId: FIREBASE_MESSAGING_SENDER_ID,
  appId: FIREBASE_APP_ID,
  measurementId: FIREBASE_MEASUREMENT_ID,
};

// Initialize Firebase
const app = getApps().length &lt; 1 ? initializeApp(firebaseConfig) : getApp();
const analytics = getAnalytics(app);
const db = getFirestore(app);
const auth = getAuth(app);

As for the packages they are also pretty standard, nothing special:
"firebase": "9.15.0", react-native, expo, rtk

Update:
Upon checking on the js debugger, after logging in it doesn't create cookies, session storage or even an indexedDB. So I think this is the reason why the user authentication does not persist, any idea on how can I fix this? I'm pretty sure it should at least generate a session or cookie after logging-in in my react native app.

答案1

得分: 0

我通过安装以下软件包成功解决了这个问题:

  • expo-application
  • @react-native-async-storage/async-storage
  • react-native-screens
英文:

I was able to fix this problem by installing these packages:

  • expo-application
  • @react-native-async-storage/async-storage
  • react-native-screens

huangapple
  • 本文由 发表于 2023年5月15日 03:14:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/76249276.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定