Search code examples
node.jsgoogle-apigmail-apiservice-accountsgoogle-api-nodejs-client

How to connect my G-Suite in nodejs server using Gmail API


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/[email protected]/labels/label_id`;
    const res = await client.request({url});
    console.log(res.data);
}

main().catch(console.error);


Solution

  • 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: "[email protected]" }
    

    So it would be like:

        const auth = new GoogleAuth({
            credentials: {
                client_email: clientEmail,
                private_key: privateKey,
            },
            scopes: 'https://mail.google.com/',
            clientOptions: { subject: "[email protected]" }
        });
    

    Reference: