使用 Google 目录 API 创建 gmail 组的权限不足

Insufficient Permission creating gmail group using Google Directory API

我想创建包含一些 email/gmails 的组。我正在使用这个 guide。这是我创建群组的代码:

SCOPES = 'https://www.googleapis.com/auth/admin.directory.group'
store = file.Storage('token.json')
creds = store.get()
if not creds or creds.invalid {
    flow = client.flow_from_clientsecrets('client_secret.json', SCOPES)
    creds = tools.run_flow(flow, store)
}
service = build('admin', 'directory_v1', http=creds.authorize(Http()))

mdig = createetag();

reqbody = {
    "kind": "admin#directory#group",
    "id": "id065468",
    "etag": "%s" % mdig,
    "email": "grpatest065469@gmail.com",
    "name": "Grptest name",
    "directMembersCount": "2",
    "description": "Grptest",
    "adminCreated": "True",
    "aliases": [
        "first@gmail.com",
        "second@gmail.com"
    ],
    "nonEditableAliases": [
    ]
}

# Call the Admin SDK Directory API
print('Creating new group')
group = service.groups()
g = group.insert(body=reqbody).execute()

我没有在我的浏览器中获得身份验证 window,不确定这是否是导致问题的原因。这是我的错误:

'kind': 'admin#directory#group', 'id': 'id065468', 'etag': "b'\x9fR\xe9O\x93\x84\xbe~\x19\xef\xd2DYJ`\x1d'", 'email': 'grptest065469@gmail.com', 'name': 'Grptest name', 'directMembersCount': '2', 'description': 'Grp test', 'adminCreated': 'True', 'aliases': ['first@gmail.com', 'second@gmail.com'],'nonEditableAliases': []

Creating new group

Traceback (most recent call last):
File ".\creategrp.py", line 105, in <module> main()
File".\creategrp.py", line 75, in main 
    g = group.insert(body=reqbody).execute()
File "C:\dev\cfehome\lib\googleapiclient\_helpers.py", line 130, in positional_wrapper
    return wrapped(*args, **kwargs)
File "C:\dev\cfehome\lib\googleapiclient\http.py", line 849, in execute 
    raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 403 when requesting https://www.googleapis.com/admin/directory/v1/groups?alt=json returned "Insufficient Permission">

您使用的凭据没有权限。这是由与 G Suite 域范围委派和/或服务帐户凭据模拟(缺少)相关的一个或多个因素造成的。

  1. 您需要创建一个服务帐户。请勿修改或更改任何权限。
  2. 您需要将全域权限委托给服务帐户。
  3. 您使用服务帐户凭据冒充另一个拥有域超级管理员权限并且至少登录 G Suite 一次并接受条款和条件的用户。

从这份关于 G Suite 域委派的文档开始:

Perform G Suite Domain-Wide Delegation of Authority

Groups: insert 需要 https://www.googleapis.com/auth/admin.directory.group 范围才能使用它。最重要的是,您已通过身份验证的用户必须有权执行您正在尝试执行的操作。您的代码似乎使用了正确的范围。

"Insufficient Permission"

可以表示以下两种情况之一。

  • 您正在验证的用户无权执行您正在尝试执行的操作
  • 您在用户登录后更改了范围。

选项一:

确保您登录的用户具有 gsuite 帐户的管理员访问权限。或者您可能想查看下面的服务帐户。

选项二:

我不是 python 开发人员,但我知道您正在使用的库。当用户在stored store = file.Storage('token.json')表示的目录中为用户登录一个凭证文件。通过在用户再次回来时执行此操作,您不必要求他们再次登录。如果您更改了范围,您需要做的就是找到该文件并将其删除。它应该弹出并再次征求您的同意。

服务帐号

如果您希望 运行 此服务器端,您可以使用 service account and set up domain wide delegation 这种方式,当脚本 运行s 服务帐户将能够应用这些更改如所须。但是,由于您似乎只是在创建一个组,如果您登录的用户无论如何都具有访问权限,则您可能不需要创建服务帐户并进行设置。

Google Api Python 客户端文档 -> Using OAuth 2.0 for Server to Server Applications