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

Google Drive API推送通知使用JWT token报Invalid Credentials错误如何解决

报错解决方案

你的401错误是由JWT配置错误、授权逻辑不符合Drive API要求、请求格式错误共同导致的,按以下步骤修正即可:

核心错误点梳理

  • JWT的aud参数配置错误:你当前用的Identity Toolkit地址是Firebase用户认证专用,和Drive API无关
  • 授权逻辑错误:你自己生成的JWT不能直接作为Bearer token调用API,需要先向Google的token接口换取正式的访问令牌
  • 缺少Drive API授权范围:你的JWT payload中没有声明Drive API的访问权限
  • 请求头格式错误:Guzzle的headers数组需要用键值对格式声明Authorization头,你当前的写法会导致头解析失败
  • 缺少必填参数:调用changes.watch接口必须先获取起始页标记pageToken,否则后续也会报错
  • 权限未配置:服务账号默认是独立账号,和你的个人Drive账号不互通,需要额外配置访问权限

修正后的完整代码

// 替换为你自己的服务账号信息
$service_account_email = "你的服务账号邮箱";
$private_key = "-----BEGIN PRIVATE KEY-----你的私钥内容-----END PRIVATE KEY-----\n";
// 替换为你要监听的Drive所属的Google账号邮箱
$target_drive_email = "你的个人Google账号邮箱";
// 替换为你验证过的webhook地址
$webhook_address = "https://你的webhook端点地址";

$now_time = time();
// 生成用于换取访问令牌的JWT
$jwt_payload = [
    "iss" => $service_account_email,
    "aud" => "https://oauth2.googleapis.com/token",
    "iat" => $now_time,
    "exp" => $now_time + 3600,
    "scope" => "https://www.googleapis.com/auth/drive",
    "sub" => $target_drive_email
];
$jwt = JWT::encode($jwt_payload, $private_key, "RS256");

$client = new \GuzzleHttp\Client();
// 第一步:用JWT换取正式访问令牌
$token_res = $client->post('https://oauth2.googleapis.com/token', [
    'form_params' => [
        'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
        'assertion' => $jwt
    ]
]);
$access_token = json_decode($token_res->getBody(), true)['access_token'];

// 第二步:获取changes起始页标记
$page_token_res = $client->get('https://www.googleapis.com/drive/v3/changes/startPageToken', [
    'headers' => [
        'Authorization' => 'Bearer ' . $access_token
    ]
]);
$start_page_token = json_decode($page_token_res->getBody(), true)['startPageToken'];

// 第三步:创建watch推送通道
$watch_res = $client->post('https://www.googleapis.com/drive/v3/changes/watch', [
    'headers' => [
        'Authorization' => 'Bearer ' . $access_token
    ],
    'json' => [
        'id' => uniqid('', true),
        'type' => 'web_hook',
        'address' => $webhook_address,
        'pageToken' => $start_page_token
    ]
]);

// 输出通道信息,保存channelId和resourceId后续停止推送时需要使用
var_dump(json_decode($watch_res->getBody(), true));

额外配置检查

  • 确认Google Cloud控制台中你对应的项目已经开启了Drive API
  • 如果你使用的是普通个人Google账号(非Workspace企业账号),不需要开启全域委派,直接打开Google Drive,给服务账号的邮箱授予你要监听的目录/全部Drive的「查看者」及以上权限即可
  • 如果你使用的是Workspace企业账号,需要先在Google Admin后台为服务账号开启全域委派权限,才能模拟组织内的用户账号
  • 你的webhook地址必须为HTTPS协议,且已经完成所有权验证,和你当前使用的Cloud项目绑定

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 05:36:05