3
votes

I have a G suite domain and open a service account with domain wide delegation. The service account also have owner identity in the project. I enable gmail API and add the scope refer to (https://developers.google.com/admin-sdk/directory/v1/guides/delegation "Delegate domain-wide authority to your service account") I enable less secure app setting too.

Here is my code:

var {google} = require('googleapis');

var jwtClient = new google.auth.JWT(
    "[email protected]",
    null,
    "-----BEGIN PRIVATE KEY-----\n....",
    ['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'] // I have also tried https://www.googleapis.com/auth/gmail.imap_admin
);

jwtClient.authorize(function(err, tokens) {
    if (err) {
      console.error(err);
      return;
    }
    console.log(tokens); // successful print the token
});

But when I use this token to try listing email: GET https://www.googleapis.com/gmail/v1/users/me/messages?access_token={access_token}

Error occurs.

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

I don't want a workaround, I intend to solve the problem with service account. I success to use the Gmail API with other authentication options. I have read many articles but none of them help. I have stuck with it for a week, any advice will be very appreciated.

I will be free to provide more detail in case it matters.

1

1 Answers

4
votes

Add a sub claim should solve this problem.

var jwtClient = new google.auth.JWT(
    "[email protected]",
    null,
    "-----BEGIN PRIVATE KEY-----\n....",
    ['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'], // I have also tried https://www.googleapis.com/auth/gmail.imap_admin
    '[email protected]' // use a user email in your domain since service account do not have Gmail box
);