Google 目录API: 使用服务帐户检索用户信息时为 403

Google Directory API: 403 when retrieving user information with service account

这可能与 Google Directory API returns 403 for user_list with showDeleted=true 有关,但遗憾的是我还无法发表评论,而且我没有答案可以提供。

我从学校的 G Suite 获得了 service account 许可

https://www.googleapis.com/auth/admin.directory.user.readonly

G Suite 管理员表示他已将 domain-wide 权限委托给该帐户,我可以创建服务帐户 JWT 并检索访问令牌以调用 APIs 使用HTTP/REST 流量。但是,当我调用 user get endpoint 请求有关帐户的信息时 -

https://www.googleapis.com/admin/directory/v1/users/redacted%40redacted.com?projection=full

我收到以下信息:

The remote server returned an error: (403) Forbidden.
{
  "error": {
    "errors": [
      {
        "domain": "global",
        "reason": "forbidden",
        "message": "Not Authorized to access this resource/api"
      }
    ],
    "code": 403,
    "message": "Not Authorized to access this resource/api"
  }
}

我无权访问他们的 G Suite 管理面板,所以我无法自行浏览,但管理员已确认我们的客户可以访问他能找到的任何地方的 admin.directory.user.readonly 权限,如上所述,我们的角色具有 domain-wide 访问权限。对于管理员可能缺少分配权限的地方,或者我的方法中可能缺少的任何内容,我愿意接受建议(尽管 JWT build/sign 和访问令牌检索 似乎是 按预期工作)。如果我可以提供任何其他有用的信息,请告诉我,我会更新。

更新:该帐户的权限似乎是正确的 - 我能够在 API 资源管理器中从 users/get 检索信息。但是,API 资源管理器正在使用 URL

https://www.googleapis.com/admin/directory/v1/users/redacted%40redacted.com?projection=full&key={YOUR_API_KEY}

而且我在服务帐户或 users/get 文档中找不到关于关键参数的任何文档。我在规范中定义的身份验证 header 中将 access_token 作为 Bearer 令牌包括在内,当我尝试将其作为关键查询字符串参数发送时,我仍然收到与上面记录的相同的 403 错误。 Stack (Google API Client users().get(userKey='name@domain.com') returns Not Authorized to access this resource/api) 上有一个类似的问题没有答案。

您需要从 google 控制台启用 API 访问

Dictionary API

Enable API

还没有玩过 Admin SDK,但我建议检查一下 Perform G Suite Domain-Wide Delegation of Authority,因为它侧重于服务帐户的使用。

Delegate domain-wide authority to your service account

The service account that you created needs to be granted access to the G Suite domain’s user data that you want to access. The following tasks have to be performed by an administrator of the G Suite domain:

  1. Go to your G Suite domain’s Admin console.
  2. Select Security from the list of controls. If you don't see Security listed, select More controls from the gray bar at the bottom of the page, then select Security from the list of controls.
  3. Select Advanced settings from the list of options.
  4. Select Manage API client access in the Authentication section.
  5. In the Client name field enter the service account's Client ID.
  6. In the One or More API Scopes field enter the list of scopes that your application should be granted access to (see image below). For example if you need domain-wide access to Users and Groups enter: https://www.googleapis.com/auth/admin.directory.user, https://www.googleapis.com/auth/admin.directory.group
  7. Click the Authorize button.

Your service account now has domain-wide access to the Google Admin SDK Directory API for all the users of your domain. You are ready to instantiate an authorized Admin SDK Directory service object on behalf of your G Suite domain's users.