【问题标题】:Not Authorized to access this resource/api while trying to access directory api尝试访问目录 api 时无权访问此资源/api
【发布时间】:2018-08-01 03:17:18
【问题描述】:

我正在使用带有googleapisgoogle-auth-library 包的节点来访问G-Suite 域的用户。为此,在启用域范围委托的情况下创建了一个服务帐户:

域管理员授予对服务帐户的访问权限以访问以下范围:

"https://www.googleapis.com/auth/admin.directory.group.readonly",
"https://www.googleapis.com/auth/admin.directory.group.member.readonly",
"https://www.googleapis.com/auth/admin.directory.user.readonly"

我的代码如下所示:

import { JWT } from "google-auth-library/build/src/auth/jwtclient";
import * as google from "googleapis";
const keys = require("../google-credentials.json");

async function main() {
  const client = new JWT(keys.client_email, undefined, keys.private_key, [
    "https://www.googleapis.com/auth/admin.directory.group.readonly",
    "https://www.googleapis.com/auth/admin.directory.group.member.readonly",
    "https://www.googleapis.com/auth/admin.directory.user.readonly"
  ]);
  await client.authorize();
  const service = google.admin("directory_v1");
  service.users.list(
    {
      auth: client,
      domain: "my_domain.com",
      maxResults: 10,
      orderBy: "email"
    },
    function(err, response) {
      if (err) {
        console.log("The API returned an error: " + err);
        return;
      }
      var users = response.users;
      if (users.length == 0) {
        console.log("No users in the domain.");
      } else {
        console.log("Users:");
        for (var i = 0; i < users.length; i++) {
          var user = users[i];
          console.log("%s (%s)", user.primaryEmail, user.name.fullName);
        }
      }
    }
  );
}

main().catch(console.error);

使用收到的服务帐户凭据初始化 JWT 客户端。不管怎样,客户端会返回以下消息:Not Authorized to access this resource/api

【问题讨论】:

标签: node.js google-admin-sdk


【解决方案1】:

您必须使用您的 google 域管理员的电子邮件来模拟服务帐户。

const client = new JWT(
      keys.client_email,
      undefined,
      keys.private_key,
      [
        "https://www.googleapis.com/auth/admin.directory.group.readonly",
        "https://www.googleapis.com/auth/admin.directory.group.member.readonly",
        "https://www.googleapis.com/auth/admin.directory.user.readonly"
      ],
      "admin@yourdomain.com"
    );

这在文档中某处的框中提到,但在任何地方都没有真正记录如何实现...

【讨论】:

  • 这对我帮助很大!我们已经是 2 位开发人员整天坐着想知道为什么云 API 可以完美运行,但目录 API 只响应“禁止”。你救了我的好朋友。
猜你喜欢
  • 2020-06-01
  • 2021-02-15
  • 2014-12-12
  • 1970-01-01
  • 2018-11-10
  • 1970-01-01
  • 2021-03-29
  • 2021-05-03
  • 2019-04-16
相关资源
最近更新 更多