我已经阅读了大量文档,尝试了数百种不同的请求,但始终收到: googleapiclient.errors.HttpError: <HttpError 403 when requesting https://www.googleapis.com/admin/directory/v1/users?domain=example.com&alt=json returned "Not Authorized to access this resource/api">
错误 .
这就是我做的:
-
在Google Developer Console https://console.developers.google.com中:
-
创建了一个新项目
-
已启用'Admin SDK' API .
-
创建了一个服务帐户密钥
-
将生成的密钥保存到'service-key.json'文件中
-
在G Suite管理控制台中:
-
API访问已启用
-
Admin SDK已启用
-
'Client ID'服务密钥^^被授权为'View users on your domain',范围:https://www.googleapis.com/auth/admin.directory.user.readonly在API客户端访问控制台部分 .
-
创建了一个简单的测试脚本:
#!/usr/bin/env python3
import json
from httplib2 import Http
from oauth2client.service_account import ServiceAccountCredentials
from apiclient.discovery import build
scopes = ['https://www.googleapis.com/auth/admin.directory.user.readonly']
credentials = ServiceAccountCredentials.from_json_keyfile_name(
'service-key.json', scopes)
account = credentials.authorize(Http())
service = build('admin', 'directory_v1', http=account)
response = service.users().list(domain='example.com').execute()
print(response)
其他:
-
也尝试'Enable G Suite Domain-wide Delegation'(在ServiceAccountCredentials对象上使用了create_delegated()方法)
-
我在Google Developer Console - Dashboard中看到脚本正在发出正确的请求 - 可以看到'directory.users.list' API方法正在发布,但因403错误而失败
在此先感谢您的帮助!
1 回答
@Rebot先生的建议对我有用 . 基本服务帐户不起作用,但模仿管理员(您已启用它),允许API调用通过 .