无法使用"google-admin-sdk"观看“管理员用户目录" [英] Not able to watch Admin Users Directory using `google-admin-sdk`
问题描述
我正在尝试使用 google-admin-sdk .我正在使用API密钥进行授权,但无法成功执行.
I am trying to connect to the G-Suite's User directory using the google-admin-sdk. I am using an API Key for authorization and I am not able to reach a successful execution.
这是我正在使用的代码代码段:
Here is the code snippet that I'm using:
import { google } from 'googleapis';
import uuid from 'uuid/v4';
const API_KEY = 'my api key goes here';
google.admin({
version: 'directory_v1',
auth: API_KEY
}).users.list({
customer: 'my_customer',
maxResults: 10,
orderBy: 'email',
}, (err, res: any) => {
if (err) { return console.error('The API returned an error:', err.message); }
const users = res.data.users;
if (users.length) {
console.log('Users:');
users.forEach((user: any) => {
console.log(`${user.primaryEmail} (${user.name.fullName})`);
});
} else {
console.log('No users found.');
}
});
输出:
Login Required
有人可以告诉我我在做什么错吗? 另外,如何进一步侦听Google API发出的事件?
Can someone tell me what I am doing wrong here? Also, how do I proceed further for listening to the events emitted by the Google API?
---更新---
以下是现在对我有用的代码段:
Here is the snippet that works for me now:
import { JWT } from 'google-auth-library';
import { google } from 'googleapis';
// Importing the serivce account credentials
import { credentials } from './credentials';
const scopes = ['https://www.googleapis.com/auth/admin.directory.user'];
const adminEmail = 'admin_account_email_address_goes_here';
const myDomain = 'domain_name_goes_here';
async function main () {
const client = new JWT(
credentials.client_email,
undefined,
credentials.private_key,
scopes,
adminEmail
);
await client.authorize();
const service = google.admin('directory_v1');
const res = await service.users.list({
domain: myDomain,
auth: client
});
console.log(res);
}
main().catch(console.error);
---奖金提示---
如果在使用目录的其他方法时遇到任何Parse Error
,请记住要JSON.stringify
请求正文.例如,在admin.users.watch
方法上:
--- Bonus Tip ---
If you face any Parse Error
s while using other methods of the directory, remember to JSON.stringify
the request body. For example, on the admin.users.watch
method:
// Watch Request
const channelID = 'channel_id_goes_here';
const address = 'https://your-domain.goes/here/notifications';
const ttl = 3600; // Or any other TTL that you can think of
const domain = 'https://your-domain.goes';
const body = {
id: channelID,
type: 'web_hook',
address,
params: {
ttl,
},
};
// Remember to put this in an async function
const res = await service.users.watch({
domain,
customer: 'my_customer',
auth: client, // get the auth-client from above
event: 'add'
}, {
headers: {
'Content-Type': 'application/json'
},
// This is the important part
body: JSON.stringify(body),
});
推荐答案
您可以在官方文档,发送给" Directory API"的每个请求都必须包含授权令牌.为了授权您的请求,您必须使用OAuth 2.0 .
As you can see in the official documentation, every request sent "to the Directory API must include an authorization token". In order to authorize your request, you have to use OAuth 2.0.
您提供的是 API密钥,它不适用于此过程. API密钥通常用于访问公共数据,而不是像您当前情况那样访问用户的私有数据.
You are providing an API key instead, which is not appropriate for this process. API keys are usually used for accessing public data, not users' private data as in your current situation.
您应遵循 Node.js快速入门代替:
- 首先,从Google API控制台获取客户端凭据.
- 第二,授权客户端:在设置用户凭据和相应的
scopes
之后获得访问令牌(该过程在快速入门中的功能authorize
和getNewToken
中完成). - 最后,一旦客户端获得授权,就调用API(功能
listUsers
).
- First, obtain client credentials from the Google API Console.
- Second, authorize the client: obtain an access token after setting the user credentials and the appropriate
scopes
(a process accomplish in functionsauthorize
andgetNewToken
in the Quickstart). - Finally, once the client is authorized, call the API (function
listUsers
).
如果要为此使用服务帐户,则必须执行以下步骤:
If you want to use a Service Account for this, you will have to follow these steps:
- 通过遵循代码可能类似于以下几行:
The code could be something along the following lines:
const {google} = require('googleapis'); const key = require('./credentials.json'); // The name of the JSON you downloaded const jwtClient = new google.auth.JWT( key.client_email, null, key.private_key, ['https://www.googleapis.com/auth/admin.directory.user'], "admin@domain" // Please change this accordingly ); // Create the Directory service. const service = google.admin({version: 'directory_v1', auth: jwtClient}); service.users.list({ customer: 'my_customer', maxResults: 10, orderBy: 'email', }, (err, res) => { if (err) return console.error('The API returned an error:', err.message); const users = res.data.users; if (users.length) { console.log('Users:'); users.forEach((user) => { console.log(`${user.primaryEmail} (${user.name.fullName})`); }); } else { console.log('No users found.'); } });
参考:
- 目录API:授权请求
- 目录API:Node.js快速入门
- 将整个域的权限委派给您的服务帐户
- Node.js的Google Auth库
- Directory API: Authorize Requests
- Directory API: Node.js Quickstart
- Delegate domain-wide authority to your service account
- Google Auth Library for Node.js
Reference:
我希望这会有所帮助.
这篇关于无法使用"google-admin-sdk"观看“管理员用户目录"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!