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

react-redux-firebase谷歌认证后,如何获取Access Token访问Google APIs

获取Google Access Token的标准方式(react-redux-firebase)

1. 在登录时直接提取Access Token

当你通过react-redux-firebase的firebase.login()完成谷歌认证时,Promise返回的结果里包含了credential对象——这里面就藏着你需要的Google Access Token。具体实现可以参考下面的代码:

export const signInWithGoogle = () => async (dispatch, getState, getFirebase) => {
  const firebase = getFirebase();
  try {
    // 发起谷歌弹窗登录,按需添加需要调用的Google API权限scope
    const authResult = await firebase.login({
      provider: 'google',
      type: 'popup',
      scopes: [
        'https://www.googleapis.com/auth/userinfo.profile',
        // 比如要调用Drive API就加这个scope,按需调整
        'https://www.googleapis.com/auth/drive.readonly'
      ]
    });

    // 从认证结果里提取Google Access Token
    const googleAccessToken = authResult.credential.accessToken;
    
    // 把token存入Redux Store,方便后续所有action都能调用
    dispatch({
      type: 'STORE_GOOGLE_ACCESS_TOKEN',
      payload: googleAccessToken
    });

    // 现在就可以用这个token调用Google API了,比如获取用户信息
    const userInfoRes = await fetch(
      'https://www.googleapis.com/oauth2/v3/userinfo',
      { headers: { Authorization: `Bearer ${googleAccessToken}` } }
    );
    const userInfo = await userInfoRes.json();
    console.log('Google用户详情:', userInfo);
  } catch (err) {
    console.error('谷歌认证失败:', err);
  }
};

2. 已登录状态下获取Token(需提前存储)

如果用户已经完成登录,后续想在其他action里调用Google API,最稳妥的方式是在登录成功时就把Access Token存入Redux Store或localStorage——因为Firebase Auth不会持久保存OAuth credential里的access token,登录后直接从auth实例里拿不到。

比如从Redux Store中读取token的示例:

export const fetchGoogleDriveFiles = () => async (dispatch, getState) => {
  // 从你的Reducer里取出之前保存的token
  const { googleAccessToken } = getState().app;
  
  if (!googleAccessToken) {
    console.error('未找到Google Access Token,请重新登录');
    return;
  }

  try {
    const res = await fetch(
      'https://www.googleapis.com/drive/v3/files',
      { headers: { Authorization: `Bearer ${googleAccessToken}` } }
    );
    const data = await res.json();
    dispatch({ type: 'SET_DRIVE_FILES', payload: data.files });
  } catch (err) {
    console.error('调用Google Drive API失败:', err);
  }
};

3. 关键注意点

  • 权限Scope:一定要在登录时请求对应Google API的scope,否则Access Token会因权限不足被拒绝调用。
  • Token过期:Google Access Token默认1小时过期,要是需要长期使用,可以在token过期时通过Firebase Auth重新触发认证获取新token,或者实现刷新逻辑。
  • getFirebase()的正确性:在redux-thunk的action creator里,第三个参数就是getFirebase(),调用它就能拿到react-redux-firebase初始化后的Firebase实例,完全可以用来处理认证和token相关操作,你之前的方向是对的~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:43:12