调用Google Drive API files->get('root')报404,疑为Scopes权限问题
调用Google Drive API获取root文件夹时出现404错误
执行以下PHP代码时,最后一行触发404(文件未找到)错误:
$result = $service->changes->getStartPageToken() ; $nextStartPageToken = $result->startPageToken ; $rootResult = $service->files->get('root')
错误日志详情:
[13-Aug-2023 20:24:47 America/New_York] PHP Fatal error: Uncaught Google\Service\Exception: { "error": { "code": 404, "message": "File not found: 0AORSlah_iew_Uk9PVA.", "errors": [ { "message": "File not found: 0AORSlah_iew_Uk9PVA.", "domain": "global", "reason": "notFound", "location": "fileId", "locationType": "parameter" } ] } } in /www/cgi-bin/GoogleRelated/vendor/google/apiclient/src/Http/REST.php:134 Stack trace: #0 /www/cgi-bin/GoogleRelated/vendor/google/apiclient/src/Http/REST.php(107): Google\Http\REST::decodeHttpResponse() #1 [internal function]: Google\Http\REST::doExecute() #2 /www/cgi-bin/GoogleRelated/vendor/google/apiclient/src/Task/Runner.php(187): call_user_func_array() #3 /www/cgi-bin/GoogleRelated/vendor/google/apiclient/src/Http/REST.php(66): Google\Task\Runner->run() #4 /www/cgi-bin/GoogleRelated/vendor/google/apiclient/src/Client.php(922): Google\Http\REST::execute() #5 /www/cgi-bin/GoogleRelated/vendor/google/apiclient/src/Service/Resource.php(238): Google\Client->execute() #6 /www/cgi-bin/GoogleRelated/vendor/google/apiclient-services/src/Drive/Resource/Files.php(205): Google\Service\Resource->call() #7 /www/htdocs/gdrive/catchupSongBook(592): Google\Service\Drive\Resource\Files->get() #8 /www/htdocs/gdrive/catchupSongBook(80): getRootFolderId() #9 {main} thrown in /www/cgi-bin/GoogleRelated/vendor/google/apiclient/src/Http/REST.php on line 134
更换另一个项目的JSON配置文件后,相同代码可正常运行。由于Google Drive不可能缺少root文件夹,怀疑是权限范围(Scopes)或项目配置问题,但未发现异常。当前请求的权限范围如下:
"https://www.googleapis.com/auth/drive.appdata" "https://www.googleapis.com/auth/drive.appfolder" "https://www.googleapis.com/auth/drive.file" "https://www.googleapis.com/auth/drive.resource"
疑问
- 该问题是否与权限范围相关?
- 当前权限范围列表是否缺少必要项?
- 能否查看实际授予的权限范围而非仅请求的?
解答
1. 该问题是否与权限范围相关?
大概率和权限范围有关。代码逻辑没问题(换项目JSON可正常运行),问题出在当前项目的权限配置或实际授予的权限上。Drive API有时会返回404而非明确的权限错误,这是一种安全机制,避免泄露文件存在的信息。
2. 当前权限范围列表是否缺少必要项?
是的,现有权限无法访问用户的Drive根目录:
drive.appdata和drive.appfolder仅能访问应用专属存储区域,无法触及用户主Drive根目录;drive.file是基于文件授权的,仅能访问用户通过该应用打开过的文件/文件夹,root文件夹不在此范围内;drive.resource是已废弃的权限,当前无效。
要访问root文件夹,至少需要添加https://www.googleapis.com/auth/drive.readonly(只读访问整个Drive),若需修改则用https://www.googleapis.com/auth/drive(全权限)。建议遵循最小权限原则,优先使用只读权限。
3. 能否查看实际授予的权限范围而非仅请求的?
可以。在PHP中,可通过Google Client对象获取已授权令牌的信息,解析出实际授予的权限范围:
$token = $client->getAccessToken(); if (isset($token['scope'])) { $grantedScopes = explode(' ', $token['scope']); print_r($grantedScopes); }
这段代码会输出当前令牌实际拥有的所有权限范围,对比请求列表即可发现差异。也可在Google Cloud Console的「OAuth同意屏幕」->「令牌管理」页面查看用户授予的权限,但代码方式更直接对应当前运行实例。
内容的提问来源于stack exchange,提问作者Dennis
相关产品推荐
相关产品推荐

