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

Google Analytics Reporting API v4权限范围不足问题求助

问题:React结合gapi调用Google Analytics Reporting API v4时出现"Request had insufficient authentication scopes"错误

我正在尝试使用React结合gapi调用Google Analytics Reporting API v4获取数据,但遇到报错:"Request had insufficient authentication scopes"。我确认access token有效,却无法解决该问题。以下是我的代码:

import React, { useEffect } from "react";
import { gapi } from "gapi-script";
import Login from "./components/login";

export default function App() {
  useEffect(() => {
    function start() {
      gapi.client.init({
        clientId: process.env.REACT_APP_CLIENT_ID,
        discoveryDocs: [
          "https://analyticsreporting.googleapis.com/$discovery/rest",
        ],
        scope:
          "https://www.googleapis.com/auth/analytics.readonly https://www.googleapis.com/auth/analytics",
      });
    }

    gapi.load("client:auth2", start);
  }, []);

  const callApi = () => {
    gapi.client.load("analyticsreporting", "v4", () => {
      // Prepare the request
      const accessToken = gapi.client.getToken().access_token;

      const batchRequest = {
        reportRequests: [
          {
            viewId: process.env.REACT_APP_VIEW_ID,
            dateRanges: [
              {
                startDate: "7daysAgo",
                endDate: "today",
              },
            ],
            metrics: [
              {
                expression: "ga:sessions",
              },
            ],
            dimensions: [
              {
                name: "ga:date",
              },
            ],
          },
        ],
      };

      // Make the request
      gapi.client.analyticsreporting.reports
        .batchGet({
          resource: batchRequest,
          headers: {
            Authorization: `Bearer ${accessToken}`, // Add the access token to the header
          },
        })
        .then((response: any) => {
          const reports = response.result.reports;
          console.log(reports);
        })
        .catch((error: any) => {
          console.error("Error fetching analytics data:", error.result.error);
        });
    });
  };

  return (
    <div>
      <Login />
      <button
        onClick={() => {
          console.log(gapi.auth.getToken().access_token);
        }}
      >
        Log token
      </button>
      <button onClick={callApi}>Call Api</button>
    </div>
  );
}

我是Google APIs新手,急需解决该问题,恳请各位提供帮助。


解决方案
  • 清除旧授权会话:浏览器会缓存Google账号的OAuth授权记录,即便你修改了作用域,旧的access token仍会沿用之前的权限。打开Google账号设置,进入「安全」-「第三方应用访问权限」,找到你的应用并移除授权,然后重启React应用重新登录,新生成的token会包含正确的作用域。
  • 简化作用域配置:读取Analytics数据只需要analytics.readonly权限,无需同时配置analytics,修改scope为:
    scope: "https://www.googleapis.com/auth/analytics.readonly"
    
  • 检查Login组件授权逻辑:确保Login组件的授权流程和gapi.client.init中的作用域一致,比如如果组件使用gapi.auth2.getAuthInstance().signIn(),要同步使用相同的scope参数。
  • 移除手动添加的Authorization头:gapi.client会自动处理权限头,手动添加可能导致冲突,删除这段代码:
    headers: {
      Authorization: `Bearer ${accessToken}`, // 移除该行
    }
    
  • 验证token作用域:用JWT解码工具解析access token,查看其中的scope字段,确认是否包含https://www.googleapis.com/auth/analytics.readonly,如果没有则说明授权过程未正确获取权限。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 11:47:57