我在公司的Google云端硬盘上有一个电子表格,我希望服务帐户可以读取该电子表格。我已经对此坚持了一段时间,但我无法弄清我所缺少的。
为此,我创建了一个服务帐户,启用了域范围的委派,并在G Suite管理员面板中添加了所需的范围(“ https://www.googleapis.com/auth/drive”和“ https://www.googleapis.com/auth/spreadsheets.readonly”),以匹配我的服务帐户的客户端ID。我为此服务帐户创建了一个密钥,并将其保存在json文件中(文件为key_sa.json)。
尽管运行以下代码时,它失败:
SERVICE_ACCOUNT_JSON_FILE_PATH = 'key_sa.json'
SCOPES = ['https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/spreadsheets.readonly']
credentials = ServiceAccountCredentials.from_json_keyfile_name(
SERVICE_ACCOUNT_JSON_FILE_PATH, scopes=SCOPES)
delegated_credentials = credentials.create_delegated('[email protected]')
delegated_http = delegated_credentials.authorize(httplib2.Http())
delegated_credentials.refresh(delegated_http)
service = build('sheets', 'v4', http=delegated_http) # credentials=credentials)
我在最后一行收到的错误消息是:
oauth2client.client.HttpAccessTokenRefreshError: unauthorized_client: Client is unauthorized to retrieve access tokens using this method, or client not authorized for any of the scopes requested.
关于我所缺少的任何提示吗?
尝试如下所述添加以下范围:
'https://www.googleapis.com/auth/drive',
'https://www.googleapis.com/auth/spreadsheets.readonly',
'https://www.googleapis.com/auth/spreadsheets'
这些范围必须同时添加到您的代码和Google管理员安全设置中的API权限中。
...spreadsheets.readonly
...spreadsheets
以上两种权限的行为都不同,因此都需要添加。