我正在使用包含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);
&#13;
使用为服务帐户收到的凭据初始化JWT客户端。无论如何,客户端都会回复以下消息:Not Authorized to access this resource/api
答案 0 :(得分:3)
您必须使用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"
],
"admin@yourdomain.com"
);
这是在一个框中的文档中的某处提到的,但是没有真正记录在任何地方如何实现...