You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用getRedirectResult拉取Google OAuth用户数据并存入Firebase Firestore

解决Google OAuth重定向登录后同步数据到Firestore的问题

1. 配置Google认证提供者并触发重定向登录

先初始化Google认证提供者,请求所需权限(包含邮箱、基础资料、出生日期),再触发重定向登录:

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

const provider = new GoogleAuthProvider();
// 请求必要权限,出生日期需额外添加专属scope
provider.addScope('email');
provider.addScope('profile');
provider.addScope('https://www.googleapis.com/auth/user.birthday.read');

// 启动Google重定向登录流程
const auth = getAuth();
signInWithRedirect(auth, provider);

2. 页面加载时处理重定向结果并写入Firestore

在页面初始化(比如App组件挂载、登录页加载)时,调用getRedirectResult获取登录结果,提取用户数据后同步到Firestore:

import { getAuth, getRedirectResult } from "firebase/auth";
import { getFirestore, doc, setDoc } from "firebase/firestore";

const auth = getAuth();
const db = getFirestore();

// 处理Google登录重定向结果
async function handleGoogleLoginResult() {
  try {
    const result = await getRedirectResult(auth);
    if (result) {
      const user = result.user;
      const additionalUserInfo = result.additionalUserInfo;

      // 仅在用户首次通过Google注册时创建文档,避免重复写入
      if (additionalUserInfo.isNewUser) {
        // 从Google用户信息中提取字段
        const [first_name, last_name] = user.displayName?.split(' ') || ['', ''];
        const email = user.email;
        // 注意:出生日期需用户授权,且部分用户可能未公开,若user对象中无数据需后续通过Google People API补充
        const date_of_birth = user.birthday || '';
        const date_created = new Date().toISOString();

        // 写入Firestore
        await setDoc(doc(db, "accounts", user.uid), {
          user_id: user.uid,
          first_name,
          last_name,
          date_of_birth,
          email,
          // Google OAuth用户无需存储密码
          date_created
        });
      }
    }
  } catch (error) {
    console.error("处理Google登录结果失败:", error);
  }
}

// 页面加载时执行
handleGoogleLoginResult();

关键注意事项

  • 出生日期获取限制:即使添加了user.birthday.read权限,Google也不会主动返回所有用户的出生日期——部分用户可能未公开该信息,或需单独调用Google People API获取(需额外配置API密钥与OAuth客户端)。
  • 姓名拆分逻辑:user.displayName是用户的全名,按空格拆分仅适用于"名+姓"的常规格式,若涉及复姓、无空格全名等特殊情况,需调整逻辑或引导用户后续补充完善。
  • 重复写入规避:通过additionalUserInfo.isNewUser判断是否为首次登录,避免每次Google登录都覆盖Firestore文档;若需同步用户后续更新的Google资料,可改为先查询文档再选择性更新。

内容的提问来源于stack exchange,提问作者Hrutvik Palutla

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 20:12:44