使用服务帐户返回400的Google API调用“无效输入”错误

发布于 2025-02-06 14:49:07 字数 3310 浏览 3 评论 0 原文

我正在尝试创建一个Google服务帐户来制作用户帐户 更改我们的Google Workspace实例。我按照说明 在页面上。 也就是说,我已经

  1. 在我们的Google Cloud Project中创建了一个服务帐户。

  2. 为该服务帐户创建了一个键,并下载了该密钥的JSON字符串版本。

  3. 在管理面板中,将服务帐户添加到“安全> api Controls”

  4. 添加了范围 https://www.googleapis.com/auth/admin.directory.user.user 在域范围内的委托书部分中的该服务帐户。

我正在运行的代码是这样的:

import os.path

from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build
from google.oauth2 import service_account

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

def main():
    creds = service_account.Credentials.from_service_account_file(
        'credentials.json', scopes=SCOPES)
    service = build('admin', 'directory_v1', credentials=creds)
    results = service.users().list(customer='my_customer', maxResults=10,
                                   orderBy='email').execute()
    users = results.get('users', [])

    if not users:
        print('No users in the domain.')
    else:
        print('Users:')
        for user in users:
            print(u'{0} ({1})'.format(user['primaryEmail'],
                                      user['name']['fullName']))

if __name__ == '__main__':
    main()

文件 recortentials.json (在某些编辑后)看起来像这样:

{
  "type": "service_account",
  "project_id": "myproject-uat1",
  "private_key_id": "f19f6e738923406283302659fbdde8abdsbeb2fd",
  "private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvg...Wo\n-----END PRIVATE KEY-----\n",
  "client_email": "[email protected]",
  "client_id": "116674234874240871478",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://oauth2.googleapis.com/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/myproject-uat-a%40myproject-uat1.iam.gserviceaccount.com"
}

当我运行上面时,我会得到此结果:

Traceback (most recent call last):
  File "/root/test.py", line 31, in <module>
    main()
  File "/root/test.py", line 17, in main
    results = service.users().list(customer='my_customer', maxResults=10,
  File "/usr/local/lib/python3.9/dist-packages/googleapiclient/_helpers.py", line 130, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "/usr/local/lib/python3.9/dist-packages/googleapiclient/http.py", line 938, in execute
    raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 400 when requesting https://admin.googleapis.com/admin/directory/v1/users?customer=my_customer&maxResults=10&orderBy=email&alt=json returned "Invalid Input". Details: "[{'message': 'Invalid Input', 'domain': 'global', 'reason': 'invalid'}]">

这个问题类似于这个stackoverflow问题但不幸的是,这个问题的答案并没有帮助我。

I am trying to create a Google service account to make user account
changes in our Google Workspace instance. I have followed the instructions
on the page "Perform Google Workspace Domain-Wide Delegation of Authority".
That is, I have

  1. Created a service account in our Google Cloud Project.

  2. Created a key for that service account and downloaded the JSON string version of that key.

  3. Added the service account to "Security > API Controls > Domain-wide Delegation" in the admin panel for our instance.

  4. Added the scope https://www.googleapis.com/auth/admin.directory.user to that service account in the Domain-wide Delegation section.

The code I am running is this:

import os.path

from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build
from google.oauth2 import service_account

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

def main():
    creds = service_account.Credentials.from_service_account_file(
        'credentials.json', scopes=SCOPES)
    service = build('admin', 'directory_v1', credentials=creds)
    results = service.users().list(customer='my_customer', maxResults=10,
                                   orderBy='email').execute()
    users = results.get('users', [])

    if not users:
        print('No users in the domain.')
    else:
        print('Users:')
        for user in users:
            print(u'{0} ({1})'.format(user['primaryEmail'],
                                      user['name']['fullName']))

if __name__ == '__main__':
    main()

The file credentials.json (after some redacting) looks like this:

{
  "type": "service_account",
  "project_id": "myproject-uat1",
  "private_key_id": "f19f6e738923406283302659fbdde8abdsbeb2fd",
  "private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvg...Wo\n-----END PRIVATE KEY-----\n",
  "client_email": "[email protected]",
  "client_id": "116674234874240871478",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://oauth2.googleapis.com/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/myproject-uat-a%40myproject-uat1.iam.gserviceaccount.com"
}

When I run the above I get this result:

Traceback (most recent call last):
  File "/root/test.py", line 31, in <module>
    main()
  File "/root/test.py", line 17, in main
    results = service.users().list(customer='my_customer', maxResults=10,
  File "/usr/local/lib/python3.9/dist-packages/googleapiclient/_helpers.py", line 130, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "/usr/local/lib/python3.9/dist-packages/googleapiclient/http.py", line 938, in execute
    raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 400 when requesting https://admin.googleapis.com/admin/directory/v1/users?customer=my_customer&maxResults=10&orderBy=email&alt=json returned "Invalid Input". Details: "[{'message': 'Invalid Input', 'domain': 'global', 'reason': 'invalid'}]">

This question is similar to this StackOverflow question but the answers to that question, unfortunately, did not help me.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

蓝梦月影 2025-02-13 14:49:07

我认为您需要使用 create_delegated 来创建凭据(使用服务帐户)代表允许使用Workspace Admin API的管理员用户操作。

请参阅:示例

I think you need to use create_delegated to create credentials (using the Service Account) delegated to operate on behalf of an admin user that is permitted to use the Workspace Admin APIs.

See: example

野却迷人 2025-02-13 14:49:07

基于Dazwilkin的答案,并参考原始问题,添加第五步:

  1. 在您的Google管理员面板中创建(或使用现有)用户,并将该用户添加到“用户管理管理员”角色(在“帐户&GT; admin下)角色”)。

如果上述步骤中的用户称为 ,应将原始问题中的代码更改为

creds = service_account.Credentials.from_service_account_file(
         'credentials.json', scopes=SCOPES, subject="[email protected]")

Based on to DazWilkin's answer, and referring to the original question, add a fifth step:

  1. In your Google's admin panel create (or use an existing) user and add that user to the "User Management Admin" role (under "Account > Admin Roles").

If the user in the above step is called [email protected], the code in the original question should then be changed to

creds = service_account.Credentials.from_service_account_file(
         'credentials.json', scopes=SCOPES, subject="[email protected]")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文