无法使用“google-admin-sdk”观看管理员用户目录
Not able to watch Admin Users Directory using `google-admin-sdk`
我正在尝试使用 google-admin-sdk 连接到 G-Suite 的用户目录。我正在使用 API 密钥进行授权,但无法成功执行。
这是我正在使用的代码片段:
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?
发出的事件
---更新---
这是现在适合我的代码片段:
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
方法上:
// 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),
});
如您在 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 密钥通常用于访问 public 数据,而不是您当前情况下的用户私人数据。
您应该按照 Node.js Quickstart 中提供的步骤进行操作:
- 首先,从 Google API 控制台获取客户端凭据。
- 其次,授权客户端:在设置用户凭据和适当的
scopes
后获取访问令牌(此过程在快速入门中的函数 authorize
和 getNewToken
中完成)。
- 最后,一旦客户端被授权,调用API(函数
listUsers
)。
更新:
如果您想为此使用服务帐户,您将必须执行以下步骤:
- 通过关注 the steps specified here.
向服务帐户授予全域委派
- 在云控制台中,为服务帐户创建私钥并下载相应的 JSON 文件。将其复制到您的目录。
- 使用服务帐户模拟有权访问此资源的用户(管理员帐户)。这是通过在创建 JWT 身份验证客户端时指示用户的电子邮件地址来实现的,如下面的示例所示。
代码可能如下所示:
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.');
}
});
参考:
- Directory API: Authorize Requests
- Directory API: Node.js Quickstart
- Delegate domain-wide authority to your service account
- Google Auth Library for Node.js
希望对您有所帮助。
我正在尝试使用 google-admin-sdk 连接到 G-Suite 的用户目录。我正在使用 API 密钥进行授权,但无法成功执行。
这是我正在使用的代码片段:
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?
发出的事件---更新---
这是现在适合我的代码片段:
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
方法上:
// 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),
});
如您在 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 密钥通常用于访问 public 数据,而不是您当前情况下的用户私人数据。
您应该按照 Node.js Quickstart 中提供的步骤进行操作:
- 首先,从 Google API 控制台获取客户端凭据。
- 其次,授权客户端:在设置用户凭据和适当的
scopes
后获取访问令牌(此过程在快速入门中的函数authorize
和getNewToken
中完成)。 - 最后,一旦客户端被授权,调用API(函数
listUsers
)。
更新:
如果您想为此使用服务帐户,您将必须执行以下步骤:
- 通过关注 the steps specified here. 向服务帐户授予全域委派
- 在云控制台中,为服务帐户创建私钥并下载相应的 JSON 文件。将其复制到您的目录。
- 使用服务帐户模拟有权访问此资源的用户(管理员帐户)。这是通过在创建 JWT 身份验证客户端时指示用户的电子邮件地址来实现的,如下面的示例所示。
代码可能如下所示:
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.');
}
});
参考:
- Directory API: Authorize Requests
- Directory API: Node.js Quickstart
- Delegate domain-wide authority to your service account
- Google Auth Library for Node.js
希望对您有所帮助。