1
votes

I want to get access to my G-Suite account in a nodejs server, using Gmail API. I understood I should create Service Account and authenticate with its credentials. I tried many examples and ways but couldn't make it works.

This is the last try I've made. returns 400 bad request.

code: 400, errors: [ { domain: 'global', reason: 'failedPrecondition', message: 'Bad Request' } ]

const {GoogleAuth} = require('google-auth-library');
const credentials = require('./sevice-account-credentials.json');

async function main() {
    const clientEmail = credentials.client_email;
    const privateKey = credentials.private_key;
    if (!clientEmail || !privateKey) {
        throw new Error(`
      The CLIENT_EMAIL and PRIVATE_KEY environment variables are required for
      this sample.
    `);
    }
    const auth = new GoogleAuth({
        credentials: {
            client_email: clientEmail,
            private_key: privateKey,
        },
        scopes: 'https://mail.google.com/',
    });
    const client = await auth.getClient();
    const projectId = await auth.getProjectId();
    const url = `https://www.googleapis.com/gmail/v1/users/my-gsuite@domain.co.il/labels/label_id`;
    const res = await client.request({url});
    console.log(res.data);
}

main().catch(console.error);
1
Please edit your question and include the full error message. Before you do anything you will need to set up domain wide deligation - DaImTo
thanks. I've added the error. domain wide delegation is set to true. - mabruk
just to make it clear: domain wide delegation is true and still throws this error. - mabruk
Hi, I posted an answer regarding this. Could you please clarify whether that solves your issue? - Iamblichus

1 Answers

1
votes

Issue:

You are not impersonating any account in the domain. That's the point of domain-wide delegation: impersonating / acting on behalf of another account.

Solution:

You have to specify which account you want the Service Account to act on behalf of, by providing the property clientOptions when instantiating GoogleAuth:

clientOptions: { subject: "my-gsuite@domain.co.il" }

So it would be like:

    const auth = new GoogleAuth({
        credentials: {
            client_email: clientEmail,
            private_key: privateKey,
        },
        scopes: 'https://mail.google.com/',
        clientOptions: { subject: "my-gsuite@domain.co.il" }
    });

Reference: