从 aws lambda 访问 Google API:无效的 OAuth 范围

Accessing Google API from aws lambda : Invalid OAuth scope

我仍在为 Google 的 api 和服务术语苦苦挣扎,但我的目标是通过 aws lambda 实现自动化功能,该功能作用于 G Suite 帐户(域?)或更具体的用户这个域名。

现在我只想列出该域的所有用户。我运行此代码在本地进行测试。

我做了什么:

这是实现:

const { google } = require("googleapis");

const auth = new google.auth.GoogleAuth({
keyFile: "credentials.json",
scopes:
  "https://www.googleapis.com/auth/drive.readonly,https://www.googleapis.com/admin/directory/v1, https://www.googleapis.com/auth/admin.directory.group, https://www.googleapis.com/auth/admin.directory.user",
 });

const service = google.admin({ version: "directory_v1", auth });
service.users.list(
{
  domain: "my.domain.com",
  maxResults: 10,
  orderBy: "email",
},
(err, res) => {
  if (err) return console.error("The API returned an error:", err.message);

  const users = res.data.users;
  if (users.length) {
    console.log("Users:");
    users.forEach((user) => {
      console.log(`${user.primaryEmail} (${user.name.fullName})`);
    });
  } else {
    console.log("No users found.");
  }
}
);

我不确定为什么我必须在 GoogleAuth 对象中添加范围,但我从 google 文档中获取了它。

当我 运行 出现以下错误时:

The API returned an error: invalid_scope: Invalid OAuth scope or ID token audience provided.

  • 目录API只能由管理员使用
  • 服务帐户不是管理员
  • 如果服务帐号要代表管理员,您需要
    • 启用 G Suite 全域委派(就像您已经做的那样)
    • 通过设置要模拟的用户将服务帐户模拟为管理员

一般来说,当您使用服务帐户时,您需要构建身份验证流程,如 documentation 中所述,即您需要创建 JSON Web 令牌 (JWT) 指定要模拟的用户。

Javascript 的示例代码片段:

        const jwtClient = new google.auth.JWT(
            privatekey.client_email,
            null,
            privatekey.private_key,
            scopes,
            user // User who will be impersonated (needs to be an admin)
        );

        await jwtClient.authorize();

        return jwtClient;