我正在尝试将匿名用户升级到他们的 Google 凭据,并使用与匿名实例相同的 uid...
无论我做什么,它都会创建一个新用户......这是为什么?
我非常感谢帮助,我真的陷入困境,并且文档没有多大帮助,因为它不完整。
https://firebase.google.com/docs/auth/web/anonymous-auth
import React, { useState } from 'react';
import { initializeApp } from 'firebase/app';
import { getAuth, signInWithPopup, GoogleAuthProvider, linkWithCredential, signInAnonymously } from 'firebase/auth';
// Initialize Firebase with your config
const firebaseConfig = {
// your config here
};
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
const AuthComponent = () => {
const signInWithGoogle = async () => {
try {
const provider = new GoogleAuthProvider();
const result = await signInWithPopup(auth, provider);
// If the user is currently signed in anonymously, link their accounts
if (auth.currentUser && auth.currentUser.isAnonymous) {
const credential = GoogleAuthProvider.credentialFromResult(result);
await linkWithCredential(auth.currentUser, credential);
console.log('Anonymous account upgraded');
} else {
// Handle successful sign in
console.log('Google sign-in success', result.user);
}
} catch (error) {
console.error('Error with Google sign-in or account linking', error);
}
};
return (
<button onClick={signInWithGoogle}>Sign In with Google</button>
);
};
export default AuthComponent;
您没有严格遵循说明。 文档说(强调我的):
当用户注册时,完成用户身份验证提供程序的登录流程直至(但不包括)调用 Auth.signInWith 方法之一。
您不应该使用 signInWith 方法,因为该方法会登录用户并为其创建一个新帐户(如果尚未创建帐户)。
文档接着说:
将 AuthCredential 对象传递给登录用户的链接方法
然后展示如何使用
linkWithCredential
将 Google 帐户凭据链接到匿名用户帐户(而不是 signInWithPopup)。