Search code examples
oauth-2.0google-apijwtgmail-apigoogle-api-nodejs-client

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


I am trying to fetch all emails under our company domain. I am using Node.js client library. In my last approach I used Oauth method as documented in quickstart guide. It was suggested that I should use JWT to authorize, but I am still unable to figure out how to do it properly in node (due to lack of documentation). This is my code:

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

I get error :

{ 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' } ] }

I am unable to understand the right approach. I want to skip any user interaction and fetch all mails under domain by running CRON job node.js scripts from the server. I have all admin rights. What is wrong in my approach?


Solution

  • Try changing your jwt format to

    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
    );
    

    Based from Perform Google Apps Domain-Wide Delegation of Authority code sample(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)
    

    Hope this helps!