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

Firebase更新密码遇auth/requires-recent-login错误,重认证无效

问题分析

你的代码核心问题是异步操作未正确等待完成,导致重认证流程还没结束就调用了updatePassword,依然触发auth/requires-recent-login错误。具体问题点:

  • reauthWithGoogle函数中,reauthenticateWithPopup是异步操作,但仅用.then()处理,未通过await等待认证完成。这会导致await reauthWithGoogle()实际上不会等待弹窗认证结束,直接执行后续的updatePassword。
  • reauthUser调用updatePassword时,没有确保重认证的Promise已完成,时序逻辑混乱。
修复方案

修改三个函数的异步逻辑,确保所有操作按顺序执行:

1. 修正reauthWithGoogle函数

用await处理弹窗认证,确保函数等待认证完成后再返回:

const reauthWithGoogle = async (): Promise<void> => {
  const auth = getAuth();
  googleProvider.setCustomParameters({ prompt: "select_account" });

  if (auth.currentUser) {
    try {
      await reauthenticateWithPopup(auth.currentUser, googleProvider);
      console.log("reauthenticateWithPopup success");
    } catch (error) {
      alert("Error reauthenticateWithPopup: " + (error as Error).message);
    }
  } else {
    router.push(ROUTES.signin);
  }
};

2. 修正reauthUser函数

确保reauthWithGoogle完成后再调用updatePassword,用try/catch统一处理错误:

const reauthUser = async (password: string): Promise<void> => {
  const auth = getAuth();
  const user = auth.currentUser;

  if (!user) {
    router.push(ROUTES.signin);
    return;
  }

  const providerId = user.providerData[0]?.providerId;
  console.log("providerId: ", providerId);

  if (providerId === "google.com") {
    try {
      await reauthWithGoogle();
      await updatePassword(user, password);
      console.log("Password updated!");
    } catch (error) {
      console.log("Error in reauthUser: " + (error as Error).message);
    }
  } else {
    alert("Unsupported authentication provider.");
  }
};

3. 修正updateUserPassword函数

改为异步函数,确保调用reauthUser时等待其完成:

async function updateUserPassword(password: string): Promise<void> {
  const auth = getAuth();
  const user = auth.currentUser;

  if (!user) {
    console.log("User is not authenticated");
    return;
  }

  try {
    await updatePassword(user, password);
    console.log("Password updated!");
  } catch (error: unknown) {
    const errMsg = (error as Error).message;
    console.log("Error updateUserPassword: " + errMsg);
    if (errMsg.includes("auth/requires-recent-login")) {
      console.log("Trigger reauthUser");
      await reauthUser(password);
    }
  }
}
额外注意事项
  • Firebase重认证会话有效期为几分钟,但必须确保重认证操作完全完成后再执行改密码这类敏感操作。
  • 若问题仍存在,可尝试在重认证后调用auth.currentUser.reload()刷新用户会话,再执行updatePassword。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 18:44:54