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

如何从Firebase Auth中获取Google API refresh token?

解决方案

你通过Firebase Auth封装的Google登录方法拿不到Google API的refresh token,是Firebase的设计限制:Firebase仅在内部管理Google refresh token用于自身登录态维护,不会通过credentialFromResult将该值暴露给前端。

推荐你使用Chrome扩展原生的身份认证API走OAuth流程,完全不需要依赖gapi库,具体操作步骤如下:


方案:使用chrome.identity API完成Google OAuth授权

前置配置

  • 在Google Cloud Console创建OAuth 2.0客户端ID,应用类型选择「Chrome扩展」,填写你的扩展ID,保存后得到client_id和client_secret
  • 确保OAuth同意屏幕配置了你需要的Google API权限,测试状态下需要将测试用户账号加入白名单
  • 在扩展的manifest.json中声明identity权限,以及OAuth相关的跳转规则

授权流程代码实现

  1. 构造带必要参数的Google授权URL,必须添加access_type=offline和prompt=consent参数才能拿到refresh token
const authUrl = new URL("https://accounts.google.com/o/oauth2/v2/auth");
authUrl.searchParams.set("client_id", "你的Google Cloud客户端ID");
authUrl.searchParams.set("redirect_uri", chrome.identity.getRedirectURL());
authUrl.searchParams.set("response_type", "code");
authUrl.searchParams.set("access_type", "offline");
authUrl.searchParams.set("prompt", "consent");
authUrl.searchParams.set("scope", "你需要的API权限范围,比如https://www.googleapis.com/auth/userinfo.email");
  1. 调用Chrome扩展身份API唤起授权页,获取授权code
const authResult = await chrome.identity.launchWebAuthFlow({
  url: authUrl.toString(),
  interactive: true
});
// 从返回的跳转URL中提取授权code
const code = new URL(authResult).searchParams.get("code");
  1. 用授权code换取access token和refresh token
const tokenRes = await fetch("https://oauth2.googleapis.com/token", {
  method: "POST",
  headers: {
    "Content-Type": "application/x-www-form-urlencoded"
  },
  body: new URLSearchParams({
    code,
    client_id: "你的Google Cloud客户端ID",
    client_secret: "你的Google Cloud客户端密钥",
    redirect_uri: chrome.identity.getRedirectURL(),
    grant_type: "authorization_code"
  })
});
const tokenData = await tokenRes.json();
// 这里就能拿到refresh token
const { access_token, refresh_token, expires_in } = tokenData;
// 存储到扩展本地存储
await chrome.storage.local.set({ refreshToken: refresh_token });

刷新access token代码

token过期后直接调用接口刷新,不需要用户重新授权:

const refreshAccessToken = async () => {
  const { refreshToken } = await chrome.storage.local.get("refreshToken");
  const res = await fetch("https://oauth2.googleapis.com/token", {
    method: "POST",
    headers: {
      "Content-Type": "application/x-www-form-urlencoded"
    },
    body: new URLSearchParams({
      client_id: "你的Google Cloud客户端ID",
      client_secret: "你的Google Cloud客户端密钥",
      refresh_token: refreshToken,
      grant_type: "refresh_token"
    })
  });
  const newTokenData = await res.json();
  return newTokenData.access_token;
}

补充说明

如果你坚持使用Firebase Auth,无法通过前端接口直接获取Google的refresh token,只能在后端服务中通过Firebase Admin SDK关联用户的Google身份后获取,不适用于无后端的Chrome扩展场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 21:06:03