How to use JWT to access Google Directory (Admin SDK) using NodeJS client libraries?

I am trying to create a server application that will add / remove users to my domain groups. Please note that it will not have any user interaction, this is a server-server application.

I registered my application in the Google API console, downloaded the key and converted it to .pem, releasing

openssl pkcs12 -in my_google_key.p12 -out my_google_key.pem -nocerts -nodes 

Then I got into the Domain Administration, Security → Advanced Settings → Authentication → OAuth Client Access Control. There I added an entry in authorized API clients. I used the client ID that I received from the service account in the console and used the scope:

https://www.googleapis.com/auth/admin.directory.group.

I installed googleapis for nodejs using

 npm install googleapis 

And here is my code:

 var googleapis = require('googleapis'); var SERVICE_ACCOUNT_EMAIL = 'My Service Account E-mail Address'; var SERVICE_ACCOUNT_KEY_FILE = 'my_google_key.pem'; // The .pem file is at the root of my application var jwt = new googleapis.auth.JWT( SERVICE_ACCOUNT_EMAIL, SERVICE_ACCOUNT_KEY_FILE, null, ['https://www.googleapis.com/auth/admin.directory.group'] ); var client; googleapis .discover('admin', 'directory_v1') .execute(function(err, data) { client = data; jwt.authorize(function(err, result) { console.log(jwt); client.admin.groups.list({ "customer": "my_customer", // This is actually "my_customer" "domain": "domain.com" // The domain name I administer }) .withAuthClient(jwt) .execute(function(err, result) { console.log(err); console.log(result); }); }); }); 

And the result of running this code is:

 { errors: [ { domain: 'global', reason: 'forbidden', message: 'Not Authorized to access this resource/api' } ], code: 403, message: 'Not Authorized to access this resource/api' } 

What am I missing? How do I enable my application using the admin SDK?

+6
source share
1 answer

1) Make sure that you are delegating domain authority for your service account.

2) Service accounts must impersonate someone who has access to the Admin SDK directory APIs.

Enable it during initialization:

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

This documentation section details both of these issues : https://developers.google.com/admin-sdk/directory/v1/guides/delegation#delegate_domain-wide_authority_to_your_service_account

+7
source

All Articles