我可以限制 Google API 服务帐户的可用范围吗?

Can I limit the available scopes on a Google API service account?

我做了以下事情:

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

当您创建 OAuth 客户端 ID 时,您可以将其限制在预定义的范围内。据我所知,服务帐户可以访问任何 Google 驱动器范围。我想将其缩小到以下范围:https://www.googleapis.com/auth/drive.readonly 只是为了保证 Google 云端硬盘应用程序不会无意中 adds/edits/deletes 任何文件。

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

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

Service accounts are special Google accounts that can be used by applications to access Google APIs programmatically via OAuth 2.0. A service account uses an OAuth 2.0 flow that does not require human authorization. Instead, it uses a key file that only your application can access.

例如:

在 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.">

参考文献: