我正在使用带有
googleapis
和 google-auth-library
包的节点来访问 G-Suite 域的用户。为此,创建了一个启用域范围委托的服务帐户:
域管理员授予服务帐户访问以下范围的权限:
"https://www.googleapis.com/auth/admin.directory.group.readonly",
"https://www.googleapis.com/auth/admin.directory.group.member.readonly",
"https://www.googleapis.com/auth/admin.directory.user.readonly"
我的代码如下所示:
import { JWT } from "google-auth-library/build/src/auth/jwtclient";
import * as google from "googleapis";
const keys = require("../google-credentials.json");
async function main() {
const client = new JWT(keys.client_email, undefined, keys.private_key, [
"https://www.googleapis.com/auth/admin.directory.group.readonly",
"https://www.googleapis.com/auth/admin.directory.group.member.readonly",
"https://www.googleapis.com/auth/admin.directory.user.readonly"
]);
await client.authorize();
const service = google.admin("directory_v1");
service.users.list(
{
auth: client,
domain: "my_domain.com",
maxResults: 10,
orderBy: "email"
},
function(err, response) {
if (err) {
console.log("The API returned an error: " + err);
return;
}
var users = response.users;
if (users.length == 0) {
console.log("No users in the domain.");
} else {
console.log("Users:");
for (var i = 0; i < users.length; i++) {
var user = users[i];
console.log("%s (%s)", user.primaryEmail, user.name.fullName);
}
}
}
);
}
main().catch(console.error);
JWT 客户端使用收到的服务帐户凭据进行初始化。不管怎样,客户端返回了以下消息:
Not Authorized to access this resource/api
您必须使用您的 Google 域管理员的电子邮件来模拟服务帐户。
const client = new JWT(
keys.client_email,
undefined,
keys.private_key,
[
"https://www.googleapis.com/auth/admin.directory.group.readonly",
"https://www.googleapis.com/auth/admin.directory.group.member.readonly",
"https://www.googleapis.com/auth/admin.directory.user.readonly"
],
"[email protected]"
);
这在文档中的某个地方提到过,但是没有真正记录如何实现...