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

Flutter调用tokenInfo API偶发无详情400错误求助

排查Google Auth tokenInfo API偶发400错误的原因与调试方案

问题背景

通过以下代码获取用户授权的Google Auth权限范围:

final oauth2Api = Oauth2Api(client);

final tokenInfo = await oauth2Api.tokeninfo();

final grantedScopes = tokenInfo.scope;

其中client通过extension_google_sign_in_as_googleapis_auth包获取,已确认不为空。但tokenInfo API会偶发抛出400错误:

DetailedApiRequestError (DetailedApiRequestError(status: 400, message: No error details. HTTP status was: 400.))

错误出现概率低于10%,但影响应用核心流程。


可能的问题原因

  • 令牌过期或临时无效:Google Sign-In虽自动刷新令牌,但网络波动、刷新窗口期内可能出现短暂的无效令牌,此时调用tokenInfo会返回400。
  • 网络波动或API限流:Google API有请求频率限制,短时间高频调用可能触发限流;网络不稳定导致请求不完整,服务器也会返回400。
  • 令牌权限同步延迟:极少情况下,生成的令牌未同步获得访问tokenInfo API的权限,权限同步延迟引发偶发400。
  • 包版本兼容性冲突:extension_google_sign_in_as_googleapis_auth与googleapis_auth、google_sign_in版本不兼容,导致令牌格式或请求头不符合API要求。

调试与解决方法

  • 预检查令牌有效性:调用tokenInfo前,先判断令牌是否过期,若过期则主动刷新:
    if (client.credentials.expiry.isBefore(DateTime.now())) {
      await client.refreshCredentials();
    }
    final tokenInfo = await oauth2Api.tokeninfo();
    
  • 添加错误重试机制:针对偶发400实现指数退避重试,避免单次错误中断流程:
    int retryCount = 0;
    const maxRetries = 3;
    TokenInfo? tokenInfo;
    
    while (retryCount < maxRetries) {
      try {
        tokenInfo = await oauth2Api.tokeninfo();
        break;
      } on DetailedApiRequestError catch (e) {
        if (e.status == 400 && retryCount < maxRetries - 1) {
          retryCount++;
          await Future.delayed(Duration(milliseconds: 100 * (1 << retryCount)));
        } else {
          rethrow;
        }
      }
    }
    final grantedScopes = tokenInfo?.scope;
    
  • 启用请求日志排查:拦截HTTP请求,记录请求头、令牌信息和响应状态,定位具体问题:
    final loggedClient = http.Client()
      ..send = (request) async {
        print('Request URL: ${request.url}');
        print('Authorization Header: ${request.headers['Authorization']}');
        final response = await (client as AuthClient).send(request);
        print('Response Status: ${response.statusCode}');
        return response;
      };
    final oauth2Api = Oauth2Api(loggedClient);
    
  • 校验包版本兼容性:确保extension_google_sign_in_as_googleapis_auth、googleapis_auth、google_sign_in使用相互兼容的稳定版本,查看包的CHANGELOG是否有相关错误修复记录。
  • 手动验证令牌:错误发生时,提取令牌(注意脱敏),手动调用https://oauth2.googleapis.com/tokeninfo?access_token=YOUR_TOKEN,查看具体错误提示,明确是令牌无效还是权限问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 05:58:35