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

时间:2016-09-10 15:44:28

标签: oauth-2.0 google-api jwt gmail-api google-api-nodejs-client

我正在尝试获取公司域下的所有电子邮件。我正在使用Node.js客户端库。在我上一篇approach中,我使用了快速入门指南中记录的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 job node.js脚本来跳过任何用户交互并获取域下的所有邮件。我拥有所有管理权限。我的做法有什么问题?

1 个答案:

答案 0 :(得分:0)

尝试将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)

希望这有帮助!