【问题标题】:Delegating access in Google API / Python在 Google API / Python 中委派访问
【发布时间】:2016-04-19 06:04:39
【问题描述】:

所以我运行了一个 Python 应用程序,它使用我们域中的服务帐户。这一切正常,服务帐户已被授予对正确范围的访问权限。我正在使用从 Google 示例之一中提取的以下内容:

from __future__ import print_function
import httplib2
import os
import pprint
import sys

from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials

"""Email of the Service Account"""
SERVICE_ACCOUNT_EMAIL = 'service_account_email@google'

"""Path to the Service Account's Private Key file"""
SERVICE_ACCOUNT_CLIENT_FILE_PATH = 'My Project-xxxxxx.json'

def main():
  scopes = ['https://www.googleapis.com/auth/drive.metadata.readonly']
  credentials = ServiceAccountCredentials.from_json_keyfile_name(
            SERVICE_ACCOUNT_CLIENT_FILE_PATH,
            scopes=scopes
        )

  http = httplib2.Http()

  http = credentials.authorize(http)

  service = build('drive', 'v3', http=http)

  results = service.files().list(
      pageSize=10,fields="nextPageToken, files(id, name)").execute()
  items = results.get('files', [])
  if not items:
      print('No files found.')
  else:
      print('Files:')
      for item in items:
          print('{0} ({1})'.format(item['name'], item['id']))

if __name__ == '__main__':
    main()

这将成功检索服务帐户的文档。现在我的理解是我应该能够委派访问权限,以便我可以作为另一个用户运行。所以我添加以下行:

delegated_credentials = credentials.create_delegated("user.name@org_domain.org.au")

然后在授权时使用 deletegated_credentials。在这一点上,我得到了错误

oauth2client.client.HttpAccessTokenRefreshError: access_denied: 请求的客户端未授权。

所以我的假设是我指定的用户无权访问 API。这是正确的方法还是我遗漏了一些明显的东西?

【问题讨论】:

    标签: python google-drive-api google-api-python-client


    【解决方案1】:

    发现我的错误,在这里为后代发布。我在 python 代码中的范围不正确,没有意识到它需要与管理客户端中授予的范围完全匹配!

    admin客户端中的作用域如下;

    https://www.googleapis.com/auth/admin.reports.audit.readonly https://www.googleapis.com/auth/drive

    现在代码中的作用域是;

    scopes = ['https://www.googleapis.com/auth/admin.reports.audit.readonly','https://www.googleapis.com/auth/drive']
    

    我知道我不需要报告范围,但关键是如果它们不匹配,那么它将不起作用。

    菜鸟失误!

    【讨论】:

    猜你喜欢
    • 2017-07-26
    • 1970-01-01
    • 2018-06-18
    • 2017-06-19
    • 2014-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-15
    相关资源
    最近更新 更多