DEV Community

wimdenherder
wimdenherder

Posted on

Impersonating a google service account

PS: this blog is not very clear, just a reminder for myself in the future, when I encounter something similar. Sorry!

  • Create a google cloud project
  • Enable Drive API
  • Create service account credentials
  • Login as admin in your domain and
  • Follow the steps here:

https://developers.google.com/identity/protocols/oauth2/service-account#httprest

install

npm init
npm install googleapis
npm install google-auth-library

create a file index.js and replace the email and credentials path below:

const { google } = require('googleapis');
const { GoogleAuth } = require('google-auth-library');
const fs = require('fs');

async function listFiles(auth) {
  const drive = google.drive({ version: 'v3', auth });

  try {
    const response = await drive.files.list({
      pageSize: 10, // Adjust this value to control the number of files returned per request (max: 1000)
      fields: 'nextPageToken, files(id, name, mimeType)',
    });

    const files = response.data.files;
    if (files.length) {
      console.log('Files:');
      files.forEach((file) => {
        console.log(`${file.name} (${file.id})`);
      });
    } else {
      console.log('No files found.');
    }
  } catch (error) {
    console.error('Error fetching file list:', error);
  }
}

async function main() {
  const SERVICE_ACCOUNT_FILE = 'YOURCREDENTIALS.json'; // Replace with the actual path to your service account credentials JSON file

  const auth = new GoogleAuth({
    keyFile: SERVICE_ACCOUNT_FILE,
    scopes: ['https://www.googleapis.com/auth/drive'],
    clientOptions: {
      subject: 'EMAIL@DOMAIN.COM' // Replace with email to impersonate
    },
  });

  const client = await auth.getClient();
  listFiles(client);
}

main();
Enter fullscreen mode Exit fullscreen mode

It was hard to find the right way, so that's why I wrote this blog to help myself and others!

Top comments (0)