daniil_
daniil_

Reputation: 980

JWT google-auth-library - bad request (400, failedPrecondition)

I try to get emails from gmail by Google API/Jwt authorizaton (by google-auth-library). It's my code:

var google = require('googleapis');
var gmail = google.gmail('v1');
var key = require('../jwt.keys.json');

var jwtClient = new google.auth.JWT(
    key.client_email,
    null,
    key.private_key,
    ['https://mail.google.com/', 
    'https://www.googleapis.com/auth/gmail.readonly', 
    'https://www.googleapis.com/auth/gmail.modify', 
    'https://www.googleapis.com/auth/gmail.metadata']
);


jwtClient.authorize(function(err, tokens) {
    if (err) {
      console.log(err);
      return;
    }
    gmail.users.messages.list({
        auth: jwtClient,
        maxResults: 5,
        q: "",
        labelIds: ["INBOX"],
        userId: 'me',
    }, function(err, response) {
        if (err)
            return d.reject('The API returned an error: ' + err);

        //...


    });
});

I get the next error for the gmail.users.messages.list request:

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

P.S. Gmail API is enabled.

Thank you!

Upvotes: 1

Views: 628

Answers (1)

sillicon
sillicon

Reputation: 232

You should not be using a JWT for a single user application like Gmail, unless you have a G Suite(Google Apps for Work domain), and that email account is with in it.

Service accounts are their own account and they're not Gmail accounts. They work well for APIs that don't need a user (e.g. maps, search) or when you are using a Google Apps for Work domain and want delegation enabled for all users in the domain (by domain admin, so you don't need individual user authorization).

More detailed answer here: https://stackoverflow.com/a/29778137/6890794

You need to apply Oauth2 to your workflow, not JWT. https://developers.google.com/gmail/api/auth/web-server

Upvotes: 1

Related Questions