Abhay Aradhya
Abhay Aradhya

Reputation: 11

List Messages using Gmail API NodeJS authorization error

I wrote a simple code to list the messages from my gmail account. However, on I get a 401 error. My code is as below

const gmailKey = google.gmail({version: 'v1', oauth2Client});

var initialRequest = gmailKey.users.messages.list({
    'userId': 'me'
});
getPageOfMessages(initialRequest, []);

var getPageOfMessages = function(request, result) {
    request.execute(function(resp) {
        result = result.concat(resp.messages);
        var nextPageToken = resp.nextPageToken;
            if (nextPageToken) {
                request = gmail.users.messages.list({
                    'userId': 'me',
                    'pageToken': nextPageToken
                });
                getPageOfMessages(request, result);
            }else{
                callback(result);
            }
    });
};

And the error is

code: 401,
errors:
[{ domain: 'global',
   reason: 'required',
   message: 'Login Required',
   locationType: 'header',
   location: 'Authorization' }]

The oauth2Client is as below

const oauth2Client = new google.auth.OAuth2(
    CLIENT_ID,
    CLIENT_SECRET,
    REDIRECT_URL
);

I used the same oauth2Client to get the access token and also have verified the same in the .credentials subsection. I also ensured that the oauth2Client initializing the gmailKey contains the appropriate credentials.

How can I resolve the gmail authorization problem?

Thanks in Advance

Upvotes: 1

Views: 1177

Answers (2)

temiyemi
temiyemi

Reputation: 31

If you're still having this issue, the problem with not setting the authorisation is in the first line of code you pasted:

const gmailKey = google.gmail({version: 'v1', oauth2Client});

The correct way to set oauth2Client is:

const gmailKey = google.gmail({version: 'v1', auth: oauth2Client });

or

google.options({ auth: oauth2Client }); // sets globally const gmailKey = google.gmail('v1');

Upvotes: 3

Linda Lawton - DaImTo
Linda Lawton - DaImTo

Reputation: 117301

'Login Required',

Means exactly that you need to be authenticated in order to access a users data.

You may want to consult Authorizing Your App with Gmail or this but its drive you will have to alter it slightly Oauth2 user agent

var GoogleAuth; // Google Auth object.
function initClient() {
  gapi.client.init({
      'apiKey': 'YOUR_API_KEY',
      'clientId': 'YOUR_CLIENT_ID',
      'scope': 'https://www.googleapis.com/auth/drive.metadata.readonly',
      'discoveryDocs': ['https://www.googleapis.com/discovery/v1/apis/drive/v3/rest']
  }).then(function () {
      GoogleAuth = gapi.auth2.getAuthInstance();

      // Listen for sign-in state changes.
      GoogleAuth.isSignedIn.listen(updateSigninStatus);
  });
}

If you are using node you could try the node.js quickstart

Upvotes: 0

Related Questions