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

Chrome扩展MV3中Firebase谷歌认证获取凭证失败求助

解决Chrome扩展Manifest V3中Firebase登录的invalid-credential错误

将Chrome扩展升级至Manifest V3后,无法使用Firebase UI登录,改用chrome.identity.launchWebAuthFlow获取id_token并通过Firebase signInWithCredential登录时,出现400错误及auth/invalid-credential的FirebaseError。

核心问题及修复步骤

1. Nonce未同步到Firebase验证流程

生成的nonce需在创建GoogleAuthProvider凭证时传入,Firebase会验证id_token中的nonce是否与传入值一致,否则判定凭证无效。

2. 重定向URI配置错误

chrome.identity.getRedirectURL()返回的地址必须添加到Google Cloud控制台OAuth 2.0客户端ID的已授权重定向URI列表中,同时确保Firebase项目与该客户端ID关联。

3. 优化id_token解析方式

原代码用字符串截取易导致解析错误,改用URLSearchParams更可靠。

修改后的完整代码

function launchGoogleAuthFlow(interactive) {
  return new Promise((resolve, reject) => {
    console.log('launching webauthflow')
    const manifest = chrome.runtime.getManifest();
    const clientId = manifest.oauth2.client_id;
    const redirectUri = chrome.identity.getRedirectURL();
    const nonce = Math.random().toString(36).substring(2, 15);

    const authUrl = new URL('https://accounts.google.com/o/oauth2/v2/auth');
    authUrl.searchParams.set('client_id', clientId);
    authUrl.searchParams.set('response_type', 'id_token');
    authUrl.searchParams.set('redirect_uri', redirectUri);
    authUrl.searchParams.set('scope', 'openid profile email');
    authUrl.searchParams.set('nonce', nonce);
    authUrl.searchParams.set('prompt', 'consent');

    chrome.identity.launchWebAuthFlow(
      { url: authUrl.href, interactive },
      (redirectedTo) => {
        if (chrome.runtime.lastError) {
          console.log(chrome.runtime.lastError.message);
          resolve(null);
          return;
        }
        const params = new URL(redirectedTo).searchParams;
        const idToken = params.get('id_token');
        resolve({ idToken, nonce });
      }
    );
  });
}

launchGoogleAuthFlow(true).then((authData) => {
  if (!authData?.idToken) {
    console.error('The OAuth token was null');
    return;
  }
  console.log('token:' + authData.idToken);
  const credential = GoogleAuthProvider.credential(authData.idToken, null, authData.nonce);
  console.log(credential);
  signInWithCredential(auth, credential).then((result) => {
    showMain();
    document.getElementById('loggedInAs').textContent = result.user.email;
    console.log("Success!!!");
    console.log(result);
  }).catch((error) => {
    console.log(error);
  });
});
console.log('finished authflow');

额外检查项

  • 确认Google Cloud控制台中,OAuth客户端ID类型为Chrome应用,且已正确填写扩展ID。
  • 检查Firebase控制台身份验证-登录方法中,Google登录已启用并关联正确的OAuth客户端ID。
  • 确保manifest.json中oauth2字段配置正确:
"oauth2": {
  "client_id": "你的客户端ID",
  "scopes": ["openid", "profile", "email"]
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 06:10:50