Skip to content

"The API returned an error: GaxiosError: Invalid Credentials" while calling Gmail API #476

@gutnichenkoanna

Description

@gutnichenkoanna

Summary

I receive this error when launch my script to check Gmail letter.

Expected Behavior

Script can login to mailbox and return the list of emails

Actual Behavior

Script returns 401 , Invalid Credentials error

Steps to Reproduce the Problem

I've done all steps according to Gmail API documentation

  1. Set up a new project on the Google Developers Console and enable the Gmail API.
    2.Log in Developers Console and create credentials for OAuth 2.0. My credentials are:
{
  "web": {
    "client_id": "357436760233-o9d8v52n7hqbbrd4t0mmue2elbrj2isr.apps.googleusercontent.com",
    "project_id": "wahitest-393910",
    "auth_uri": "https://accounts.google.com/o/oauth2/auth",
    "token_uri": "https://oauth2.googleapis.com/token",
    "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
    "client_secret": "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",
    "redirect_uris": [
      "https://localhost"
    ]
  }
}
  1. Installed googleapis package for Gmail API and google-auth-library for OAuth 2.0.
  2. Wrote and launched Node.js script:
const {google} = require('googleapis');
const readline = require('readline');
const fs = require('fs');

// Constants for Gmail API access
const SCOPES = ['https://www.googleapis.com/auth/gmail.readonly',
    'https://mail.google.com/',
    'https://www.googleapis.com/auth/gmail.modify',
    'https://www.googleapis.com/auth/gmail.compose',
    'https://www.googleapis.com/auth/gmail.send'];
const TOKEN_PATH = 'credentials.json';
const CREDENTIALS_PATH = 'credentials.json';

// Load the client credentials from a file
fs.readFile(CREDENTIALS_PATH, (err, content) => {
    if (err) {
        console.error('Error loading client credentials:', err);
        return;
    }

    // Authorize the client
    authorize(JSON.parse(content), listMessages);
});

// Create an OAuth2 client
function authorize(credentials, callback) {
    var client_secret = credentials.client_secret;
    var client_id = credentials.client_id;
    var redirect_uris = credentials.redirect_uris;

    const oAuth2Client = new google.auth.OAuth2(
        client_id, client_secret, redirect_uris);

// Check if we have previously stored a token.
    fs.readFile(TOKEN_PATH, (err, token) => {
        if (err) return getAccessToken(oAuth2Client, callback);
        oAuth2Client.setCredentials(
            {
                access_token: token
            }
        );
        callback(oAuth2Client);
    });
}

// Get a new token by prompting the user to visit an authorization URL
// and enter the authorization code
function getNewToken(oAuth2Client, callback) {
    const authUrl = oAuth2Client.generateAuthUrl({
        access_type: 'offline',
        scope: SCOPES,
    });
    console.log('Authorize this app by visiting this URL:', authUrl);
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout,
    });
    rl.question('Enter the code from that page here: ', (code) => {
        rl.close();
        oAuth2Client.getToken(code, (err, token) => {
            if (err) {
                console.error('Error retrieving access token:', err);
                return;
            }
            oAuth2Client.setCredentials(token);
            fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
                if (err) {
                    console.error('Error writing token to file:', err);
                }
                console.log('Token stored to', TOKEN_PATH);
            });
            callback(oAuth2Client);
        });
    });
}

// List the most recent emails in the mailbox
function listMessages(auth) {
    const gmail = google.gmail({version: 'v1', auth});

    gmail.users.messages.list(
        {
            userId: 'me',
            maxResults: 10, // You can change the number of emails to fetch here
        },
        (err, res) => {
            if (err) {
                console.error('The API returned an error:', err);
                return;
            }
            const messages = res.data.messages;
            if (messages.length) {
                console.log('Most recent emails:');
                messages.forEach((message) => {
                    console.log('- %s', message.id);
                });
            } else {
                console.log('No emails found.');
            }
        }
    );
}

That is what I receive as response:

headers: {
      'x-goog-api-client': 'gdcl/6.0.4 gl-node/18.12.1',
      'Accept-Encoding': 'gzip',
      'User-Agent': 'google-api-nodejs-client/6.0.4 (gzip)',
      Authorization: 'Bearer {"web":{"client_id":"357436760233-83l1fn2pg1kajgm7jc0s49pa6078q96n.apps.googleusercontent.com","project_id":"wahitest-393910","auth_uri":"https://accounts.google.com/o/oauth2/auth","token_uri":"https://oauth2.googleapis.com/token","auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs","client_secret":"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","redirect_uris":["http://localhost"]}}',
      Accept: 'application/json'
    },
    params: { maxResults: 10 },
    validateStatus: [Function (anonymous)],
    retry: true,
    responseType: 'json',
    retryConfig: {
      currentRetryAttempt: 0,
      retry: 3,
      httpMethodsToRetry: [Array],
      noResponseRetries: 2,
      statusCodesToRetry: [Array]
    }
  },
  code: 401,

I tried different ports to redirect_uris, it did not help, I can't authenticate

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions