【问题标题】:Receiving 403 error when accessing G Suite Admin SDK using google-api-python-client使用 google-api-python-client 访问 G Suite Admin SDK 时收到 403 错误
【发布时间】:2018-04-22 20:02:55
【问题描述】:

我正在尝试编写一个简单的脚本,该脚本将使用 google-api-python-client 从我的 Google G Suite 域从 Admin SDK 的 Directory API 获取用户列表。我阅读了大量文档,尝试了数百种不同的请求,但总是收到:googleapiclient.errors.HttpError: <HttpError 403 when requesting https://www.googleapis.com/admin/directory/v1/users?domain=example.com&alt=json returned "Not Authorized to access this resource/api"> 错误。

这就是我所做的:

  1. 在 Google 开发者控制台https://console.developers.google.com

    • 创建了一个新项目
    • 已启用“Admin SDK”API。
    • 创建了服务帐号密钥
    • 将生成的密钥保存到“service-key.json”文件中
  2. 在 G Suite 管理控制台中:

  3. 创建了一个简单的测试脚本:

    #!/usr/bin/env python3
    
    import json
    from httplib2 import Http
    from oauth2client.service_account import ServiceAccountCredentials
    from apiclient.discovery import build
    
    scopes = ['https://www.googleapis.com/auth/admin.directory.user.readonly']
    
    credentials = ServiceAccountCredentials.from_json_keyfile_name(
        'service-key.json', scopes)
    
    account = credentials.authorize(Http())
    service = build('admin', 'directory_v1', http=account)
    response = service.users().list(domain='example.com').execute()
    
    print(response)
    

其他:

  • 还尝试了“启用 G Suite 域范围委派”(在 ServiceAccountCredentials 对象上使用了 create_delegated() 方法)
  • 我在 Google 开发者控制台 - 仪表板中看到,脚本正在发出正确的请求 - 可以看到正在发出 'directory.users.list' API 方法,但失败并出现 403 错误

提前感谢您的帮助!

【问题讨论】:

  • 尝试impersonating 成为您域的管理员,因为您已经能够启用域范围的委派。如链接所述,“当您的服务帐户请求并且不是域的管理员时,它无法访问 Admin SDK Directory API。”希望这会有所帮助。
  • 你如何在 python 中做到这一点?例如。上面的代码会是什么样子?
  • @Elliptica 您可以查看this 答案以获取 Python 解决方案

标签: python python-3.x google-api google-admin-sdk google-api-python-client


【解决方案1】:

@Mr.Rebot 的建议对我有用。基本服务帐户不起作用,但冒充管理员(您已启用它)允许 API 调用通过。

【讨论】:

    猜你喜欢
    • 2018-05-11
    • 1970-01-01
    • 2018-10-20
    • 2021-01-28
    • 1970-01-01
    • 1970-01-01
    • 2016-12-24
    • 2018-08-07
    • 2017-09-20
    相关资源
    最近更新 更多