1

希望你能提供帮助。

尝试通过服务帐户与 GSuite API 交互;但是,获取“客户端未经授权无法使用此方法检索访问令牌”错误。

下面的示例代码:

#!/usr/bin/env python3

# Set env, import tools and generally get started

from __future__ import print_function
import httplib2
import os
from httplib2 import Http

from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage

from oauth2client.service_account import ServiceAccountCredentials
from oauth2client.service_account import _JWTAccessCredentials

try:
    import argparse
    flags = argparse.ArgumentParser(parents= . 
[tools.argparser]).parse_args()
except ImportError:
    flags = None

service_credentials_file = 
'/Users/my.user/Documents/Github/GSuite/service_credential.json'

# change working directory to script location (required for file use)
dir_path = os.path.dirname(os.path.realpath(__file__))
os.chdir(dir_path)

scopes = ['https://www.googleapis.com/auth/admin.directory.user',]

def test_function():
    credentials = ServiceAccountCredentials.from_json_keyfile_name(service_credentials_file, scopes=scopes)
    delegated_credentials = 
credentials.create_delegated('super.admin@domain.co.uk')
    http_auth = delegated_credentials.authorize(httplib2.Http())

    service = discovery.build('admin', 'directory_v1', http=http_auth)

    print('Getting the first 10 users in the domain')
    results = service.users().list(customer='my_customer', maxResults=10, orderBy='email', domain='nnn.nn').execute()
    print(results)

if __name__ == '__main__':
    test_function()

引发完整错误:

raise HttpAccessTokenRefreshError(error_msg, status=resp.status) oauth2client.client.HttpAccessTokenRefreshError:未授权客户端:客户端未经授权无法使用此方法检索访问令牌。

到目前为止我检查过的内容:

  • 范围(在此示例中为“ https://www.googleapis.com/auth/admin.directory.user ”)已在 Admin>Security 中为此服务帐户的客户端 ID 授权
  • 为服务帐户启用了域范围的委派
  • 被模拟的帐户可以自行调用 API 进行身份验证,问题在于模拟此(和任何其他)用户,甚至只是自行授权为服务帐户。
  • 使用调用“from_p12_keyfile”方法的 .p12 密钥文件也不起作用。

这里的任何帮助都会令人惊叹,因为它已经花了一周的时间,而且我完全没有想法(就像谷歌博士一样)。

谢谢!

4

0 回答 0