GET https://admin.googleapis.com/admin/directory/v1/groups/{groupKey}/members
我无法进行这个HTTP调用。
我的代码是
from google.oauth2.credentials import Credentials
from google.auth.transport.requests import Request
from google.oauth2 import service_account
from google.auth.exceptions import RefreshError
from google.oauth2.credentials import Credentials
from google.oauth2 import service_account
import requests
# Load the service account credentials
credentials = service_account.Credentials.from_service_account_file(
'/home/key.json',
scopes=['https://apps-apis.google.com/a/feeds/groups/'
]
)
# Check if the credentials have an access token or if it's expired
if not credentials.token or credentials.expired:
try:
# Refresh the access token using the credentials
credentials.refresh(Request())
except RefreshError:
raise Exception('Failed to refresh access token')
# Get the access token from the credentials
access_token = credentials.token
print(access_token)
group_key = "test@test.ai"
# Set the API endpoint URL
url = f"https://admin.googleapis.com/admin/directory/v1/groups/{group_key}/members"
# Set the access token in the Authorization header
# access_token = "your_access_token_here"
headers = {"Authorization": f"Bearer {access_token}"}
# Make the HTTP GET request to the API endpoint with the headers
response = requests.get(url, headers=headers)
# Check if the response was successful
if response.status_code == 200:
# Get the list of members from the response JSON
members = response.json().get("members", [])
# Print the list of members
for member in members:
print(member["email"])
else:
# Print the error message if the response was not successful
print(f"Error: {response.status_code} - {response.text}")
我得到这个错误错误:403 - {"error" {"code" 403,未被授权访问此资源/api;"errors"({未被授权访问此资源/api;"domain"global"reason"forbidden"}]}}
服务帐户有以下角色:BigQuery资源查看器,文件夹查看器,组织查看器,查看器
正如您所述,当您尝试使用浏览器时,您可以看到预期的输出,因此请尝试遵循下面提到的故障排除步骤:
-
在工作空间管理控制台中为服务帐户添加以下作用域:'
https://www.googleapis.com/auth/admin.directory.group.readonly
','https://www.googleapis.com/auth/admin.directory.group.member.readonly
' -
检查
Admin SDK
是否使能,用户是否有Admin role
。 -
尝试使用此官方文档为服务帐户设置域范围的委托。
检查域名和组名中的拼写错误。
附上类似问题供参考。