google-api - 我可以限制 Google API 服务帐户的可用范围吗?
问题描述
我做了以下事情:
- 在 Google API 控制台中创建了一个项目
- 在项目中启用 Google Drive API
- 创建了一个服务帐户
- 与服务帐号共享 Google Drive 文件夹
- 成功连接到 Google Drive 并检索到与服务帐户共享的文件夹和文件列表。
创建 OAuth 客户端 ID 时,您可以将其限制在预定义的范围内。据我所知,服务帐户可以访问任何 Google Drive 范围。我想将其缩小到以下范围:https://www.googleapis.com/auth/drive.readonly
就像我保证我正在制作的 Google Drive 应用程序不会无意添加/编辑/删除任何文件一样。
我知道我可以将帐户添加到不同的角色。但是,我多次查看该列表,但没有一个与 Google Drive 相关。我尝试创建自己的角色,但该屏幕上的可用权限也不引用 Google Drive。可能我错过了什么,或者还有其他地方可以看。有什么建议么?
解决方案
要限制服务帐户的范围,您必须在服务器端指定范围。
服务帐户是特殊的 Google 帐户,应用程序可以使用这些帐户通过 OAuth 2.0 以编程方式访问 Google API。服务帐户使用不需要人工授权的 OAuth 2.0 流。相反,它使用只有您的应用程序可以访问的密钥文件。
例如:
在 python 中,您可以通过创建范围列表来指定服务帐户的范围,并在获取凭据时将其用作参数。
文件夹和文件:
Python:
搜索所有带有 jpeg 扩展名的图片:
import httplib2
import os
from apiclient import discovery
from google.oauth2 import service_account
scopes = ["https://www.googleapis.com/auth/drive.readonly"]
secret_file = os.path.join(os.getcwd(), 'client_secret.json')
credentials = service_account.Credentials.from_service_account_file(secret_file, scopes=scopes)
service = discovery.build('drive', 'v3', credentials=credentials)
page_token = None
while True:
response = service.files().list(q="mimeType='image/jpeg'",
spaces='drive',
fields='nextPageToken, files(id, name)',
pageToken=page_token).execute()
for file in response.get('files', []):
# Process change
print('Found file: %s' % (file.get('name')))
page_token = response.get('nextPageToken', None)
if page_token is None:
break
输出:
Found file: cute-puppy.jpg
创建具有只读范围的文件夹:
import httplib2
import os
from apiclient import discovery
from google.oauth2 import service_account
scopes = ["https://www.googleapis.com/auth/drive.readonly"]
secret_file = os.path.join(os.getcwd(), 'client_secret.json')
credentials = service_account.Credentials.from_service_account_file(secret_file, scopes=scopes)
service = discovery.build('drive', 'v3', credentials=credentials)
file_metadata = {
'name': 'Invoices',
'mimeType': 'application/vnd.google-apps.folder'
}
file = service.files().create(body=file_metadata,
fields='id').execute()
错误信息:
<HttpError 403 when requesting https://www.googleapis.com/drive/v3/files?fields=id&alt=json returned "Insufficient Permission: Request had insufficient authentication scopes.". Details: "Insufficient Permission: Request had insufficient authentication scopes.">
参考:
推荐阅读
- reactjs - 如何迭代 FilteredData 以及如何使用带有 Typesecript 的 Redux 在 UI 中更新
- html - 将html转换为pdf后,img仅显示白色空白方块
- visual-studio-code - 你如何在vscode中只选择整个字符串?
- java - AWS SDK V2 S3 获取对象未获取超过 1000 个的对象
- mysql - 我尝试使用 select min(select count()) 但它不起作用
- react-final-form - 反应最终形式挑战
- mysql - Mysql 服务器:我已连接到 localhost,然后当我单击服务器启动/关闭时,我收到错误消息
- elasticsearch - 由于错误,Logstash 停止处理:(LoadError) no such file to load -- bundler
- javascript - Material-UI 滑块组件:如何以不同的顺序显示值/标记?
- python - 英特尔 HPC 库:xgboost_activate.sh:16:= 未找到