首页 > 解决方案 > 使用服务帐户进行 Google Admin SDK 身份验证

问题描述

我的团队目前正在开发一个应用程序,以使用 Admin SDK 在 GCP 中列出我公司的域用户,用于入职和离职目的。

我们正在使用服务帐户来执行此操作,并且我们已经admin.directory.user.readonly在 Google 管理员的高级设置中添加了范围。Admin SDK API 已激活,我们可以在 Credentials 区域看到服务帐户。

当我们使用参数and调用https://www.googleapis.com/admin/directory/v1/users端点时,同时使用通过oauth2l生成的访问令牌,我们会收到以下消息:viewType=domain_publicdomain=[our domain]

{
   "error": {
       "errors": [
           {
               "domain": "global",
               "reason": "forbidden",
               "message": "Not Authorized to access this resource/api"
           }
       ],
       "code": 403,
       "message": "Not Authorized to access this resource/api"
   }
}

是否会应用我们没有预见到的任何域限制?

标签: google-cloud-platformgoogle-apigoogle-admin-sdkservice-accountsgoogle-directory-api

解决方案


服务帐号无权为您的 G Suite 实例调用 Directory APi。它有权做的是在您授予它访问权限的目录 API 范围的上下文中充当您域中的用户。

获取服务帐户凭据时,您需要添加 sub=admin@yourdomain.com 参数,以便您充当域管理员,而不是服务帐户。看:

https://developers.google.com/identity/protocols/OAuth2ServiceAccount

还有一些代码示例:

https://developers.google.com/admin-sdk/directory/v1/guides/delegation


推荐阅读