使用NodeJS列出Google Workspace用户的服务帐户。

huangapple go评论61阅读模式
英文:

List Google Workspace users with a service account using NodeJS

问题

我正在尝试使用服务帐号从一个简单的脚本中调用Google Directory API。
脚本应该能够列出Google Workspace中的用户。

我已经配置了一个带有服务帐号的项目并生成了密钥。
并且我已经启用了Admin SDK API。

脚本:

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

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

  const service = google.admin({ version: "directory_v1", auth });
  const res = await service.users.list({
    customer: "my_customer",
    maxResults: 10,
    orderBy: "email",
  });
})();

错误信息:

{
  ...
  code: 400,
  errors: [ { message: 'Invalid Input', domain: 'global', reason: 'invalid' } ]
}

我不明白我漏掉了什么。

英文:

I am trying to consume Google Directory API from a simple script using a Service Account.
The script should be able to list the users from Google Workspace.

I have configured a project with a service account and generated the key.
And I have enabled the Admin SDK API.

The script:

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

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

  const service = google.admin({ version: "directory_v1", auth });
  const res = await service.users.list({
    customer: "my_customer",
    maxResults: 10,
    orderBy: "email",
  });
})();

The error

{
  ...
  code: 400,
  errors: [ { message: 'Invalid Input', domain: 'global', reason: 'invalid' } ]
}

I don't see what I am missing.

答案1

得分: 1

我的节点有点生锈,但你需要将工作区域域名指定给用户。这是在该域上具有访问权限的用户。确保你已配置了域广泛的委托。

client.subject = user;

完整示例

const getClient = async (scopes: string[], user: string) => {
  const auth = new google.auth.GoogleAuth({
    credentials: SRVC_ACCOUNT_CREDS,
    scopes: scopes
  });
  const client = await auth.getClient();
  client.subject = user;
  return client;
};
英文:

My node is a bit rusty but you need to delignate to a user on the workspace domain. This is the user on the domain that has access. Make sure that you have configured domain wide deligation.

client.subject = user;

Full example

const getClient = async (scopes: string[], user: string)=>{
  const auth = new google.auth.GoogleAuth({
    credentials: SRVC_ACCOUNT_CREDS,
    scopes: scopes
  });
  const client = await auth.getClient();
  client.subject = user;
  return client;
};

huangapple
  • 本文由 发表于 2023年7月3日 23:11:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/76606038.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定