我正在实现匿名登录,但是当用户决定使用 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/