首页 > 解决方案 > 我可以限制 Google API 服务帐户的可用范围吗?

问题描述

我做了以下事情:

  1. 在 Google API 控制台中创建了一个项目
  2. 在项目中启用 Google Drive API
  3. 创建了一个服务帐户
  4. 与服务帐号共享 Google Drive 文件夹
  5. 成功连接到 Google Drive 并检索到与服务帐户共享的文件夹和文件列表。

创建 OAuth 客户端 ID 时,您可以将其限制在预定义的范围内。据我所知,服务帐户可以访问任何 Google Drive 范围。我想将其缩小到以下范围:https://www.googleapis.com/auth/drive.readonly就像我保证我正在制作的 Google Drive 应用程序不会无意添加/编辑/删除任何文件一样。

我知道我可以将帐户添加到不同的角色。但是,我多次查看该列表,但没有一个与 Google Drive 相关。我尝试创建自己的角色,但该屏幕上的可用权限也不引用 Google Drive。可能我错过了什么,或者还有其他地方可以看。有什么建议么?

标签: google-apigoogle-drive-api

解决方案


要限制服务帐户的范围,您必须在服务器端指定范围。

服务帐户是特殊的 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.">

参考:


推荐阅读