NodeJS:无法使用服务帐户访问 Gmail API

NodeJS: Fail to use service account to access Gmail API

我有一个 G 套件域,并开设了一个具有全域委托的服务帐户。服务帐户在项目中也具有所有者身份。 我启用 gmail API 并添加范围参考 (https://developers.google.com/admin-sdk/directory/v1/guides/delegation "Delegate domain-wide authority to your service account") 我也启用了不太安全的应用程序设置。

这是我的代码:

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

var jwtClient = new google.auth.JWT(
    "service@xxx.iam.gserviceaccount.com",
    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
});

但是当我使用此令牌尝试列出电子邮件时: 获取 https://www.googleapis.com/gmail/v1/users/me/messages?access_token={access_token}

发生错误。

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

我不需要解决方法,我打算使用服务帐户解决问题。我成功地将 Gmail API 与其他身份验证选项一起使用。 我读过很多文章,但其中 none 有帮助。我坚持了一个星期,任何建议将不胜感激。

如果重要,我会免费提供更多详细信息。

添加子声明应该可以解决这个问题。

var jwtClient = new google.auth.JWT(
    "service@xxx.iam.gserviceaccount.com",
    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
    'user@yourdomain.com' // use a user email in your domain since service account do not have Gmail box
);