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

google.auth Python SDK无法读取凭据文件中的已授权Scopes

问题详情

我已成功执行以下命令:

gcloud auth application-default login --client-id-file google_oauth_client_id.json --scopes="https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/calendar.calendars.readonly"

在浏览器中完成授权后,为测试应用授予了Calendar和Cloud Platform权限,凭据已保存到本地路径:

Credentials saved to file:[/home/*****/.config/gcloud/application_default_credentials.json]

但运行以下Python代码片段时,出现403权限错误:

from google.auth import default
from google.auth.transport.requests import Request
from googleapiclient.discovery import build

SCOPES = ["https://www.googleapis.com/auth/calendar.calendars.readonly"]

credentials, project_id = default(scopes=SCOPES, quota_project_id='my-project-id')
credentials.refresh(Request())
access_token = credentials.token
service = build("calendar", "v3", credentials=credentials)
events = service.events().list(calendarId="My Calendar Id", maxResults=10, singleEvents=True, orderBy="startTime").execute()

起初我怀疑是calendarId不正确,但调试时发现credentials对象未定义任何Scopes:

>>> (credentials.scopes, credentials.default_scopes, credentials.granted_scopes)
(None, None, None)

删除application_default_credentials.json文件后,default方法会抛出对应错误,说明代码确实读取了该文件,但未识别到已授权的权限。查看该凭据文件,未发现Scopes相关内容,文件包含的键为:

dict_keys(['account', 'client_id', 'client_secret', 'refresh_token', 'type', 'universe_domain'])

可能原因推测

  • Scopes存储在服务器端,刷新令牌时需要正确请求对应的Scopes;
  • gcloud客户端未将Scopes信息正确保存到本地凭据文件中。

我更倾向于第一种可能,因为CLI能正确显示并传递Scopes到OAuth授权会话。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 10:25:13