reactjs - 当 linkWithPopup 出现错误时,如何获取凭证?

标签 reactjs firebase firebase-authentication

我正在实现匿名登录,但是当用户决定使用 Google Popup 中的另一个凭据登录时,它会给我一个错误 - auth/credential-already-in-use。

我知道问题是用户已经注册,我想要实现的是,如果用户已经注册,他将根据他提供的 linkWithPopup 凭据登录到现有帐户。提供商是 Google

我认为这与 SDK 9 有关

我尝试过的:

import {
  linkWithPopup,
  signInWithCredential,
} from "firebase/auth";

const isAnnon = auth.currentUser?.isAnonymous;
const annonUser = auth.currentUser;

  try {
      const userCredential = await linkWithPopup(annonUser, provider);
  } 
  catch (e: any) {
  if (e?.code === "auth/credential-already-in-use") {
          console.log(e);
          const login = await signInWithCredential(auth, e.credential)
            .then((user) => {
              console.log(user);
            })
            .catch((e: any) => {
              console.log(e);
            });
      }
   }

当用户是新用户时它可以工作,但是当我尝试登录现有用户(没有链接)时,它不允许我,因为 e.credential 始终未定义。

我还尝试使用 .then 而不是 async,但我仍然没有获得凭据。我认为这与导入有关 - 这是新的 firebase SDK

谢谢!

最佳答案

对于那些需要此解决方案的人,我刚刚找到了!您应该从 firebase/auth 导入 GoogleAuthProvider,然后像这样使用它:

import {
  GoogleAuthProvider,
} from "firebase/auth";

GoogleAuthProvider.credentialFromError(error);

完整代码:

import {
  linkWithPopup,
  signInWithCredential,
  GoogleAuthProvider
} from "firebase/auth";

const isAnnon = auth.currentUser?.isAnonymous;
const annonUser = auth.currentUser;

  try {
      const userCredential = await linkWithPopup(annonUser, provider);
  } 
  catch (error: any) {
  if (error?.code === "auth/credential-already-in-use") {
          const credential: any = GoogleAuthProvider.credentialFromError(error);
          const login = await signInWithCredential(auth, credential)
            .then((user) => {
              console.log(user);
            })
            .catch((error: any) => {
              console.log(error);
            });
      }
   }

这非常有效!

关于reactjs - 当 linkWithPopup 出现错误时,如何获取凭证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71307223/

相关文章:

reactjs - 处理从express到react的错误响应

javascript - 从 JS 中的不可变数组中删除元素的最干净方法是什么?

javascript - 带括号的 func 和不带括号的 func 有什么区别

javascript - $firebaseArray 在保存子元素后丢失功能

javascript - Firebase,如何在日期范围内对键进行排序

firebase - Google 端点错误 : Firebase ID token has incorrect "aud" (audience) claim. 预期...但得到

javascript - 不变的JS参数不清楚

node.js - 在特定日期/时间安排云功能

javascript - Firebase Web Auth 在移动设备上不起作用?

Firebase 用户已删除但仍在设备上登录