node.jsgoogle-apigoogle-admin-sdkgoogle-api-nodejs-client

List Google Workspace users with a service account using NodeJS


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.


Solution

  • 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;
    };