微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

尝试使用 Google Directory API 和 OAuth2.0 时收到错误“未授权访问此资源/api”

如何解决尝试使用 Google Directory API 和 OAuth2.0 时收到错误“未授权访问此资源/api”

我正在编写一个 python 脚本,该脚本在我的域中创建一个新的 google 用户并将其添加到现有组中。为了确保一切设置正确,我想首先列出该组的当前成员。请注意,我已在控制台中启用了 Admin-SDK API 并创建了一个 OAuth 2.0 凭据。我的代码如下:

  1. 授权
ScopES = ['https://www.googleapis.com/auth/admin.directory.user','https://www.googleapis.com/auth/admin.directory.group','https://www.googleapis.com/auth/admin.directory.group.member']
creds = None
credsFile = os.path.abspath("pyScripts/googleCreds/credentials.json")
tokenFile = os.path.abspath("pyScripts/googleCreds/token.pickle")
if os.path.exists(tokenFile):
    with open(tokenFile,'rb') as token:
        creds = pickle.load(token)

if not creds or not creds.valid:
    if creds and creds.expired and creds.refresh_token:
        creds.refresh(Request())
    else:
        flow = InstalledAppFlow.from_client_secrets_file(
            credsFile,ScopES)
        creds = flow.run_local_server(port=0)

    with open(tokenFile,'wb') as token:
        pickle.dump(creds,token)

service = build('admin','directory_v1',credentials=creds)
  1. 创建用户
service.users().insert(body=request).execute()

这里的请求是参数的字典,如姓名和电子邮件,根据需要

  1. 列出群组中的当前成员
service.members().list(groupKey='group@domain.com').execute()

用户已成功创建,但在尝试列出群组成员时收到 403:

googleapiclient.errors.HttpError: <HttpError 403 when requesting https://admin.googleapis.com/admin/directory/v1/groups/group%40domain.com/members?alt=json returned "Not Authorized to access this resource/api">

是什么导致了这个问题?我特别困惑,因为用户端点运行良好,但成员端点不起作用。我还应该提到,我在使用 API Explorer 时看到了相同的行为。感谢任何帮助,谢谢!

解决方法

我能够重现与您相同的错误代码和消息。 如果您在群组的电子邮件地址中输入了错误的域名,则会出现此错误 403,并显示“未授权访问此资源/api”消息。

https://developers.google.com/admin-sdk/directory/reference/rest/v1/members/list?hl=en

enter image description here

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。