Google Drive API读取JPG文件注释时出现403权限不足错误的原因排查与解决咨询
我看到你在调用Google Drive API读取JPG文件注释时遇到了403权限错误,咱们一步步来分析原因和解决办法。
首先看你遇到的错误:
An error occurred: <HttpError 403 when requesting https://www.googleapis.com/drive/v2/files/1SbB4VwCIhaS9mdJ_xqcyjenZfxxrpTsY/comments?alt=json returned "Insufficient Permission: Request had insufficient authentication scopes.". Details: "[{'domain': 'global', 'reason': 'insufficientPermissions', 'message': 'Insufficient Permission: Request had insufficient authentication scopes.'}]">
错误原因分析
核心问题出在授权范围(Scopes)不匹配且权限不足:
- 你代码里定义的
SCOPES包含https://www.googleapis.com/auth/drive和drive.file,但你的token.json里实际生效的scopes是:
旧的token是基于之前的scopes生成的,不会自动更新成你现在代码里的scopes。"scopes": ["https://www.googleapis.com/auth/drive.metadata.readonly", "https://www.googleapis.com/auth/drive.file"] drive.metadata.readonly只能读取文件的元数据(比如文件名、创建时间),没有权限访问文件的评论;drive.file是基于"由应用创建或打开的文件"的权限,如果这个JPG文件不是通过你的应用创建/授权的,这个权限也无法读取它的评论。
解决步骤
更新代码里的Scopes
替换你的SCOPES定义,选择适合的权限:- 如果你只需要读取评论,用更精细的权限(推荐,遵循最小权限原则):
SCOPES = ['https://www.googleapis.com/auth/drive.comments.readonly'] - 如果你需要Drive的全权限(适合开发测试阶段):
SCOPES = ['https://www.googleapis.com/auth/drive']
- 如果你只需要读取评论,用更精细的权限(推荐,遵循最小权限原则):
删除旧的token.json并重新授权
旧的token已经绑定了之前的scopes,必须删除token.json文件,然后重新运行你的代码。运行时会弹出授权页面,让你重新授予新的权限,之后会生成新的token.json,里面的scopes就会和你代码里定义的一致了。保持Quickstart与代码的Scopes一致
如果你是从Google的Quickstart模板开始的,一定要确保Quickstart里配置的scopes和你当前代码里的SCOPES完全相同,否则重新授权时还是会用旧的scopes生成token。
验证代码示例(以只读评论权限为例)
from googleapiclient.discovery import build from google.oauth2.credentials import Credentials from googleapiclient.errors import HttpError def retrieve_comments(service, file_id): """Retrieve a list of comments. Args: service: Drive API service instance. file_id: ID of the file to retrieve comments for. Returns: List of comments. """ try: comments = service.comments().list(fileId=file_id).execute() return comments.get('items', []) except HttpError as error: print('An error occurred: %s' % error) return None # 更新后的Scopes SCOPES = ['https://www.googleapis.com/auth/drive.comments.readonly'] credentials = Credentials.from_authorized_user_file('token.json', SCOPES) service = build('drive', 'v2', credentials=credentials) print(retrieve_comments(service, '1SbB4VwCIhaS9mdJ_xqcyjenZfxxrpTsY'))
内容的提问来源于stack exchange,提问作者Sasha Casas

