如何使用JWT使用NodeJS客户端库访问Google Directory(Admin SDK)?

我正在尝试创build一个服务器应用程序,将用户添加/删除到我的域组。 请注意,它不会与用户有任何交互,它是服务器到服务器的应用程序。

我在Google API Console中注册我的应用程序,下载密钥并通过发布将其转换为.pem

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

然后我去了域pipe理,安全 – >高级设置 – >authentication – >pipe理OAuth客户端访问。 在那里,我在授权API客户端添加了一条logging。 我使用了我从Console中的服务帐户获得的客户端ID,并使用范围:

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

我安装了用于nodejs的googleapis

 npm install googleapis 

这是我的代码:

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

运行这个代码的结果是:

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

我错过了什么? 如何使用Admin SDK授权我的应用程序?

1)确保您将域的权限委托给您的服务帐户。

2)服务帐户必须模拟能够访问Admin SDK Directory API的人员。

在初始化时join它:

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

文档的这一部分详细解释了这两个部分 : https : //developers.google.com/admin-sdk/directory/v1/guides/delegation#delegate_domain-wide_authority_to_your_service_account