Search code examples
node.jsgoogle-apiauthorizationjwtgoogle-api-nodejs-client

Getting Error: unauthorized_client when trying to authorize script


I've created service account with domain wide delegation and its scopes (in Admin console and Developer console) as described in documentation. I've been trying this for a week now and I am stuck. This is my code:

const google = require('googleapis');
const gmail = google.gmail('v1');
const directory = google.admin('directory_v1');
const scopes = [
  'https://www.googleapis.com/auth/gmail.readonly',
  'https://www.googleapis.com/auth/admin.directory.user.readonly'
];
const key = require('./service_key.json');

var authClient = new google.auth.JWT(
  key.client_email,
  key,
  key.private_key,
  scopes,
  "kruno@example.com"
);

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

// API call methods here...

});

I get this error:

Error: unauthorized_client

I am unable to understand:

  • Is this proper technique for calling Google API methods from server-side scripts without any user interaction? (under domain only)
  • How do service account and actual user account communicate this way?
  • I heard about callback URI, am I missing it?

Solution

  • I think you are missing the final step which is giving access to your application in the control panel of your domain.

    You can follow doc properly to activate it with your application

    https://developers.google.com/+/domains/authentication/delegation

    Also you can start with your first call step here

    https://developers.google.com/adwords/api/docs/guides/first-api-call