2

I obtained a service account JSON file and also attached domain wide delegation permissions to that service account. Next I set the service account file path using the GOOGLE_APPLICATION_CREDENTIALS env variable. After that I tried to access google groups of the domain like this:

import { google } from 'googleapis';

const admin = await google.admin({
  version: 'directory_v1',
});

const groupsResponse = await admin.groups.list({
  domain: process.env.GOOGLE_DOMAIN,
});

This gives me the following error:

Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.

What am I missing here?

THpubs
  • 7,804
  • 16
  • 68
  • 143

1 Answers1

4

You need to apply the client to the service object.

auth: client

you may want to check out using-the-keyfile-property

Try this

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;
};
Linda Lawton - DaImTo
  • 106,405
  • 32
  • 180
  • 449
  • Thank you very much! This worked for me. For the subject, I passed the email of the admin account. – THpubs Jul 20 '22 at 05:37