尝试使用Google目录api和服务帐户身份验证时收到错误“未授权访问此资源/api”

2024-06-02 06:54:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我真的很难尝试使用服务帐户身份验证来使用Google目录API(Admin SDK)。

使用基于客户机的三条腿OAuth这是可行的(在这里测试-https://developers.google.com/admin-sdk/directory/v1/reference/members/insert),但是对我使用的服务帐户的权限委派有问题。在Google Apps管理下,我启用了api,并按照指示将服务帐户添加到允许的OAuth客户端列表中。

代码如下:

import httplib2
import sys

from apiclient.discovery import build
from oauth2client.client import SignedJwtAssertionCredentials

credentials = SignedJwtAssertionCredentials(
    '<KEY>@developer.gserviceaccount.com',
    '<KEY DATA>',
    scope='https://www.googleapis.com/auth/apps.groups.settings https://www.googleapis.com/auth/admin.directory.group https://www.googleapis.com/auth/admin.directory.group.member'
)
http = httplib2.Http()
http = credentials.authorize(http)

service = build("admin", "directory_v1", http=http)
groups = service.groups()
g = groups.get(groupKey="<GROUP NAME>").execute()

最终,我得到以下错误:

apiclient.errors.HttpError: <HttpError 403 when requesting https://www.googleapis.com/admin/directory/v1/groups/<GROUP NAME>?alt=json returned "Not Authorized to access this resource/api">

我还尝试使用了以下API:

service = build("groupssettings", "v1", http=http)

但这也会返回一个错误-“后端错误”。


Tags: httpsimportbuildcomauthhttpadminwww
1条回答
网友
1楼 · 发布于 2024-06-02 06:54:10

即使您使用的是服务帐户,您仍然需要在实例中代表具有适当管理权限的Google Apps用户行事。试着做:

credentials = SignedJwtAssertionCredentials(
  '<KEY>@developer.gserviceaccount.com',
  '<KEY DATA>',
  scope='https://www.googleapis.com/auth/apps.groups.settings https://www.googleapis.com/auth/admin.directory.group https://www.googleapis.com/auth/admin.directory.group.member',
  sub='super-admin@yourdomain.com'
)

其中super-admin@yourdomain.com是您的Google Apps帐户中的超级管理员。

相关问题 更多 >