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

React Native中Google Sign-In令牌过期处理及刷新令牌实现求助

React Native中Google Sign-In获取并使用Refresh Token实现自动刷新AccessToken

1. 基础依赖准备

确保你已经安装并配置了@react-native-google-signin/google-signin库,这是React Native中处理Google登录的主流工具。

2. 配置Sign-In选项以触发Refresh Token返回

要获取refresh token,必须在登录配置中添加两个关键参数,告知Google授权服务器返回离线访问凭证:

import { GoogleSignin } from '@react-native-google-signin/google-signin';

GoogleSignin.configure({
  scopes: ['email', 'profile'], // 按需添加所需权限
  webClientId: '你的Web客户端ID(从Google Cloud控制台获取)',
  offlineAccess: true, // 开启离线访问,对应accessType: 'offline'
  prompt: 'consent', // 强制触发授权流程,确保返回refresh token
});

3. 获取并持久化Refresh Token

登录成功后,从返回的用户信息中提取refreshToken,将其存储到本地(比如用AsyncStorage或MMKV),后续刷新token时会用到:

const signIn = async () => {
  try {
    await GoogleSignin.hasPlayServices();
    const userInfo = await GoogleSignin.signIn();
    // 持久化存储关键凭证
    await AsyncStorage.setItem('google_refresh_token', userInfo.refreshToken);
    await AsyncStorage.setItem('google_access_token', userInfo.accessToken);
    await AsyncStorage.setItem('google_token_expiry', (Date.now() + userInfo.expirationDate).toString());
  } catch (error) {
    console.error('登录失败:', error);
  }
};

4. 使用Refresh Token刷新Access Token

当access token过期时,调用Google的令牌端点获取新的access token,无需用户重新登录:

const refreshAccessToken = async () => {
  const refreshToken = await AsyncStorage.getItem('google_refresh_token');
  const clientId = '你的Web客户端ID';
  
  // 注意:纯客户端应用不要直接暴露clientSecret,建议通过后端服务转发请求
  const clientSecret = '你的Web客户端密钥(从Google Cloud控制台获取)';

  try {
    const response = await fetch('https://oauth2.googleapis.com/token', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      body: new URLSearchParams({
        client_id: clientId,
        client_secret: clientSecret,
        refresh_token: refreshToken,
        grant_type: 'refresh_token',
      }),
    });

    const data = await response.json();
    if (data.access_token) {
      // 更新本地存储的凭证
      await AsyncStorage.setItem('google_access_token', data.access_token);
      const expiryTime = Date.now() + (data.expires_in * 1000);
      await AsyncStorage.setItem('google_token_expiry', expiryTime.toString());
      return data.access_token;
    } else {
      throw new Error('刷新token失败');
    }
  } catch (error) {
    console.error('刷新token出错:', error);
    // 刷新失败时需引导用户重新登录
    await GoogleSignin.signOut();
    return null;
  }
};

5. 自动刷新逻辑建议

  • 提前触发刷新:发起API请求前,检查当前access token的过期时间,若距离过期不足5分钟,先调用refreshAccessToken获取新token。
  • 拦截401错误:在API请求拦截器中,若收到401(未授权)响应,尝试刷新token后重新发起请求,若刷新失败再引导用户登录。

6. 关键注意事项

  • 确保Google Cloud控制台中,你的OAuth 2.0 Web客户端ID已正确配置,Android应用的SHA-1指纹、iOS应用的Bundle ID已添加到授权列表。
  • prompt: 'consent'仅在首次登录或需要重新授权时弹出授权框,后续登录若用户已授权,仍会返回refresh token。
  • 不要在前端代码中暴露clientSecret,纯客户端应用建议通过后端服务调用Google令牌端点,避免密钥泄露。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 17:12:55