Thursday 20 April 2017

gmail.users.watch fails to send test message to PubSub with a DwD service account

I'm trying to setup gmail.users.watch but am getting a 403 error:

Error sending test message to Cloud PubSub projects/project-id/topics/topic-id : User not authorized to perform this action.

Authentication is working using the GOOGLE_APPLICATION_CREDENTIALS approach and the downloaded credentials json file.

The following code works correctly which supports my hypothesis that the authentication is generally working:

const pubsub = PubSub();
const topic = pubsub.topic('topic-id');
const subscription = pubsub.subscription('subscription-id');
topic.exists()
  .then(data => {
    console.log(data);
    return subscription.exists();
  })
  .then(data => {
    console.log(data);
    return subscription.pull()
  })
  .then(data => {
    data[1].receivedMessages.forEach(d => console.log(d));
    return topic.publish('Hello, world!');
  })
  .then(data => {
    console.log(data)
  })
  .catch(err => console.log(err));

No errors from that code. However the following code throws the 403 error described above:

const authParams = {
  subject: userId,
  scopes: [
    'https://mail.google.com/',
    'https://www.googleapis.com/auth/pubsub'
  ]
};

gauth.getAuth(authParams)
  .then(authClient => {
    const params = {
      auth: authClient,
      userId: 'me',
      resource: {
        topicName: <topic-id>
      }
    };

    return new Promise((resolve, reject) => {
      gmail.users.watch(params, (err, response) => {
        if (err) {
          console.log(err);
          reject(err);
        }
        resolve(response);
      });
    });
  })
  .then(response => {
    console.log(response);
  });

gauth.getAuth is a simple wrapper around getApplicationDefaultGoogle Auth Library for Node.js.

The G Suite domain security Client Access is configured with the Client ID of the service account against the scopes needed: https://www.googleapis.com/auth/pubsub, https://mail.google.com/

As the native cloud pub/sub stuff works I think the service account has all of the correct permissions configured on the console so I'm a bit at a loss as to why the gmail call is failing.



via chrisbateskeegan

No comments:

Post a Comment