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

Firebase中使用GoogleAuthProvider获取refresh token续期Google Calendar访问令牌

核心原因

Firebase Auth 返回的 Google accessToken 是标准 OAuth2 短期令牌,固定有效期1小时,Firebase 本身没有提供自动刷新这类第三方服务商令牌的能力,需要你自己通过 Google 颁发的 refreshToken 完成续期。

实现步骤

1. 调整登录配置,获取refresh_token

默认情况下Google OAuth授权只有用户第一次给你的应用授权时才会返回refresh_token,后续授权如果用户已经同意过权限就不会返回,所以需要在登录时添加自定义参数,强制用户确认授权,确保能拿到refresh_token:

const auth = getAuth();
const provider = new GoogleAuthProvider();
provider.addScope("https://www.googleapis.com/auth/calendar");
// 新增:强制用户选择账户并确认授权,保证返回refresh_token
provider.setCustomParameters({
  prompt: "consent select_account"
});
const result = await signInWithPopup(auth, provider);
const credential = GoogleAuthProvider.credentialFromResult(result);
const accessToken = credential.accessToken;
// 新增:获取refresh_token,存储到本地或你的后端数据库
const refreshToken = credential.refreshToken;
localStorage.setItem('google_calendar_refresh_token', refreshToken);
const user = result.user;
await this.checkUser(user, accessToken);

2. 实现access_token刷新逻辑

access_token过期时,用存储的refresh_token调用Google OAuth令牌接口兑换新的access_token即可:

async function refreshGoogleAccessToken() {
  const refreshToken = localStorage.getItem('google_calendar_refresh_token');
  if (!refreshToken) {
    // 无有效refresh_token时需要引导用户重新登录授权
    throw new Error('No valid refresh token, please re-login');
  }
  const response = await fetch('https://oauth2.googleapis.com/token', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    // 以下client_id、client_secret替换为你Google Cloud控制台OAuth客户端的对应配置
    body: new URLSearchParams({
      client_id: '你的Google OAuth客户端ID',
      client_secret: '你的Google OAuth客户端密钥',
      refresh_token: refreshToken,
      grant_type: 'refresh_token'
    })
  });
  const tokenRes = await response.json();
  const newAccessToken = tokenRes.access_token;
  // 若返回了新的refresh_token需要更新本地存储
  if (tokenRes.refresh_token) {
    localStorage.setItem('google_calendar_refresh_token', tokenRes.refresh_token);
  }
  return newAccessToken;
}

3. 业务侧对接逻辑

调用日历接口前可以先判断当前access_token是否过期,或者接口返回401状态码时,自动调用上述刷新方法获取新token后重试请求即可。

注意事项
  • 纯前端暴露client_secret存在泄露风险,生产环境建议把刷新token的逻辑放到你的后端服务处理,前端仅调用后端接口获取新的access_token,避免密钥泄露
  • Google的refresh_token本身长期有效,仅当用户主动撤销应用授权、连续6个月未使用该refresh_token时才会失效,失效时需要引导用户重新走登录授权流程
  • 不要把Firebase Auth的idToken和Google的accessToken混淆,前者是Firebase自身的身份凭证,无法用于调用Google日历接口

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 15:54:09