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
相关产品推荐
相关产品推荐

