Gmail API - 无法使用 google.auth.jwt 从域中的用户获取邮件

Gmail API - unable to fetch messages from users in domain using google.auth.jwt

我正在尝试获取我们公司域下的所有电子邮件。我正在使用 Node.js 客户端库。在我的上一个 中,我使用了快速入门指南中记录的 Oauth 方法。有人建议我应该使用 JWT 进行授权,但我仍然无法弄清楚如何在节点中正确地进行授权(由于缺少文档)。这是我的代码:

var google = require('googleapis'),
    gmail  = google.gmail('v1');
var key = require('./service_key.json');

var jwtClient = new google.auth.JWT(
  key.client_email,
  null,
  key.private_key,
  ['https://mail.google.com/','https://www.googleapis.com/auth/admin.directory.group']
);

jwtClient.authorize(function(err, tokens) {
  if (err) {
    console.log(err);
    return;
  }

  gmail.users.messages.list({userId: 'me', auth: jwtClient}, (err, response)=>{
      if (err) {
        console.log(err);
        return;
      }
      console.log(response);
  });//messages.list

});//jwtClient.authorize

我收到错误:

{ Error: Bad Request
    at Request._callback (/home/kunok/code/gapi/node_modules/google-auth-library/lib/transporters.js:85:15)
    at Request.self.callback (/home/kunok/code/gapi/node_modules/google-auth-library/node_modules/request/request.js:198:22)
    at emitTwo (events.js:106:13)
    at Request.emit (events.js:191:7)
    at Request.<anonymous> (/home/kunok/code/gapi/node_modules/google-auth-library/node_modules/request/request.js:1057:14)
    at emitOne (events.js:101:20)
    at Request.emit (events.js:188:7)
    at IncomingMessage.<anonymous> (/home/kunok/code/gapi/node_modules/google-auth-library/node_modules/request/request.js:1003:12)
    at emitNone (events.js:91:20)
    at IncomingMessage.emit (events.js:185:7)
  code: 400,
  errors: 
   [ { domain: 'global',
       reason: 'failedPrecondition',
       message: 'Bad Request' } ] }

我无法理解正确的方法。我想跳过任何用户交互并通过 运行 CRON 作业 node.js 脚本从服务器获取域下的所有邮件。我拥有所有管理员权限。我的方法有什么问题?

尝试将 jwt format 更改为

var jwt = new googleapis.auth.JWT(
SERVICE_ACCOUNT_EMAIL,
SERVICE_ACCOUNT_KEY_FILE,
null,
['https://www.googleapis.com/auth/admin.directory.group'],
account_with_Admin_SDK_access_to_impersonate@example.com
);

基于 Perform Google Apps Domain-Wide Delegation of Authority 代码示例 (python):

"""Build and returns an Admin SDK Directory service object authorized with the service accounts
that act on behalf of the given user.

Args:
user_email: The email of the user. Needs permissions to access the Admin APIs.
Returns:
Admin SDK directory service object.
"""

credentials = ServiceAccountCredentials.from_p12_keyfile(
SERVICE_ACCOUNT_EMAIL,
SERVICE_ACCOUNT_PKCS12_FILE_PATH,
'notasecret',
scopes=['https://www.googleapis.com/auth/admin.directory.user'])

credentials = credentials.create_delegated(user_email)

希望对您有所帮助!