question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

service account impersonating admin user gets unauthorized_client

See original GitHub issue

I’m attempting to use the Admin SDK via a service account in the context of a firebase cloud function. Per these docs I am impersonating an admin user, and have enabled directory-wide delegation (proof). The proper scope (admin.directory.user) has been granted to the API by the admin user.

const google = require('googleapis');

const KEY = require('./mykey.json');

function connect() {
  return new Promise((yep, nope) => {
    const jwtClient = new google.auth.JWT(
      KEY.client_email,
      null,
      KEY.private_key,
      ['https://www.googleapis.com/auth/admin.directory.user'],
      'adminuser@mydomain.com'
    );

    jwtClient.authorize((err) => {
      if(err) {
        nope(err);
      } else {
        yep(jwtClient);
      }
    });
  });
}

function listUsers(client) {
  return new Promise((yep, nope) => {
    google.admin('directory_v1').users.list({
      auth: client,
      domain: 'mydomain.com',
    }, (err, response) => {
      if (err) {
        return nope(err);
      }
      return yep(response);
    });
  });
}

function getAllUsers() {
  return connect().then((client) => (listUsers(client)));
}

calling getAllUsers() fails at the authorization step with unauthorized_client: Client is unauthorized to retrieve access tokens using this method. This seems to contradict everything I’ve read about DwD and service accounts. Are you able to shed some light on how this should work?

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Reactions:12
  • Comments:8 (3 by maintainers)

github_iconTop GitHub Comments

1reaction
jlippoldcommented, Aug 11, 2019

I got a service account working with the gmail api

I followed this tutorial for the google console and google admin portion: https://medium.com/lyfepedia/sending-emails-with-gmail-api-and-python-49474e32c81f

And here’s my working code that let’s me send emails on behalf of any email in my google apps domain without refreshTokens or OAuth2

var fs = require("fs-extra");
const { google } = require('googleapis');

//this is the json credentials you get from google service setip
var config = fs.readJsonSync("/Users/jed/config.json");

var sendFrom = "jed@mydomain.com";

var authClient = new google.auth.JWT(
    config.client_email, 
    null,
    config.private_key,
    ['https://www.googleapis.com/auth/gmail.send'],
    sendFrom
);

const gmail = google.gmail({
    version: 'v1',
    auth: authClient,
});

const messageParts = [
    'From: ' + sendFrom,
    'To: someone@gmail.com',
    'Content-Type: text/html; charset=utf-8',
    'MIME-Version: 1.0',
    `Subject: Poop`,
    '',
    'This is a message just to say hello.',
    'So... <b>Hello!</b>',
];
const message = messageParts.join('\n');

// The body needs to be base64url encoded.
const encodedMessage = Buffer.from(message)
    .toString('base64')
    .replace(/\+/g, '-')
    .replace(/\//g, '_')
    .replace(/=+$/, '');

gmail.users.messages.send({
    userId: sendFrom,
    requestBody: {
        raw: encodedMessage,
    },
}, function (err, res) {
    if (err) {
        console.log(err);
    } else {
        console.log(res);
    }
});
1reaction
mryersecommented, Mar 27, 2019

ghost, how can that work without telling the drive service which google account to run under the context of? When authorizing with a service account file from GCP, the service would have no idea which user (i.e. firstname.lastname@gmail.com, or something) to make the API calls for. And yet, I cannot find a single working example on this internet doing this in Node.js.

Read more comments on GitHub >

github_iconTop Results From Across the Web

unauthorized_client error when trying to impersonate an account
Meaning: A service account was authorized using the client email address rather than the client ID (numeric) in the Admin console.
Read more >
Cannot impersonate user for gmail with service account
But if I add my own email for example, it says: Couldn't connect with these settings 401 - {"error":"unauthorized_client","error_description":" ...
Read more >
Impossible to use service account without google workspace
If I try and impersonate the google account that set up the Google Adwords/Ads account I then get this error: Error:"unauthorized_client", ...
Read more >
Managing service account impersonation - IAM - Google Cloud
This page describes how to allow principals and resources to impersonate, or act as, an Identity and Access Management (IAM) service account.
Read more >
Using OAuth 2.0 for Server to Server Applications | Authorization
Google Workspace domain administrators can also grant service accounts ... access to the service account and you want to impersonate a user account, ......
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found