0

I am using node to list all users from domain. I had created service account with domain wide delegation. The domain admin gave access to the service account to required scopes.

Code:

const { JWT } = require('google-auth-library');
const {google, chat_v1} = require('googleapis');
const keys = require('./keys.json')

async function main() {
const client = new JWT(keys.client_email, keys, keys.private_key, 
    ['https://www.googleapis.com/auth/admin.directory.user', 
    'https://www.googleapis.com/auth/admin.directory.user.readonly',
    'https://www.googleapis.com/auth/cloud-platform'],
    "admin@domain.com"
    );
await client.authorize();

const service = google.admin("directory_v1");

service.users.list({
domain: "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.');
}
});
}

main();

but only thing I recive is:

The API returned an error: Login Required.

also enabled admin sdk api for this service account any idea why this is happening?

mikeyMike
  • 21
  • 4

1 Answers1

2

I'm not sure if JWT is the correct way, but this is how I do it.

const google = require("googleapis").google;
const SRVC_ACCOUNT_CREDS = require('./keys.json');

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

const listUsers = async (query = "", limit = 500, pageToken = null, user, fields, getAll = false)=>{
  const scopes = ["https://www.googleapis.com/auth/admin.directory.user"];
  const client = await getClient(scopes, user);
  const service = google.admin({version: "directory_v1", auth: client});
  const result = {
    users: [],
    nextPageToken: ""
  };
  if(!fields) { 
    fields = "users(name.fullName,primaryEmail,organizations(department,primary,title),thumbnailPhotoUrl),nextPageToken"; 
  }
  do{
    const request = await service.users.list({
      customer: "my_customer",
      fields: fields,
      orderBy: "givenName",
      maxResults: limit,
      pageToken: pageToken,
      query: query,
      viewType: "admin_view"
    });
    pageToken = getAll ? request.data.nextPageToken : null;
    const users = request.data.users;
    if(users && users.length){
      result.users.push(...users);
      result.nextPageToken = request.data.nextPageToken;
    }
  } while(pageToken);
  return result;
};
Morfinismo
  • 4,985
  • 4
  • 19
  • 36