Home > other >  Using Google Drive API from cloud function using the default service account without generating a ke
Using Google Drive API from cloud function using the default service account without generating a ke

Time:02-18

As far as I know one best practice on Google Cloud is to not use Service Account keys as much as possible.

Here I have a Google Cloud function (nodejs) accessing Drive via Drive API (googleapis package v95.0.0), using a service account key (generated file via console).

What works:

const settings = require('./config/driveSA.json');
const options = {
         googleKey: settings,
         user: '[email protected]' //user impersonification
}

const auth = gdriveUtils.prepareJwt(google, options);

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

const file = await drive.files.get({
    fileId: fileId,
    alt: 'media',
    supportsTeamDrives: true,
});

What I want to achieve:

I want to improve this function, making it directly use the default service account inherited by the Cloud Function itself (which is the same referred by the key).

This approach always works when using '@google-cloud' related packages. Like for Storage we can simply:

const storage = new Storage();
const bucket = storage.bucket(bucketName);

What I tried:

Without specifying any auth obj:

const drive = google.drive({ version: 'v3' });

const file = await drive.files.get({
    fileId: fileId,
    alt: 'media',
    supportsTeamDrives: true,
});

Using a not-really-documented method: getApplicationDefault

import { GoogleApis, Auth } from 'googleapis';
const adcResponse = await google.auth.getApplicationDefault();
const auth: Auth.GoogleAuth = new google.auth.GoogleAuth(adcResponse);
const drive = google.drive({ version: 'v3', auth: auth });

const file = await drive.files.get({
    fileId: fileId,
    alt: 'media',
    supportsTeamDrives: true,
});

Unfortunately the package's documentation is always vague about the authentication part and always use keys in the examples. Is this something viable? Or am I forced to use a key in this case?

Thanks!

CodePudding user response:

As user @DalmTo mentions, you are most likely mixing the accounts. Please keep in mind the fact that there are 2 service accounts involved when using the GCP services and the Google API services: The GCP service account: Which Cloud Functions is using (most likely the App Engine default service account) when you invoke the function. The Google API service account: Which has the privileges on your drive to perform all sort of actions.

If you would like to be able to perform all those activities in your drive, ensure you are using the Google API service account in your function, this is most easily done through the account key as you mention.

  • Related