简体   繁体   English

尝试访问目录api时无权访问此资源/ api

[英]Not Authorized to access this resource/api while trying to access directory api

I am using node with the googleapis and google-auth-library packages for accessing the users of G-Suite domain. 我将带有googleapisgoogle-auth-library包的节点用于访问G-Suite域的用户。 For that a service account was created with the domain-wide-delegation enabled: 为此,创建了一个启用了域范围委派的服务帐户:

全域授权

The domain admin gave access to the service account to access following scopes: 域管理员授予访问服务帐户的权限,以访问以下范围:

"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"

My code looks like this: 我的代码如下所示:

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

A JWT client get initialised with the credentials received for the service account. JWT客户端使用为服务帐户收到的凭据进行初始化。 Whatever, the client gives the following message back: Not Authorized to access this resource/api 无论如何,客户端都会返回以下消息: Not Authorized to access this resource/api

You have to impersonate the service account with an email of a admin of your google domain. 您必须使用您的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"
    );

This is mentioned somewhere in the docs in a box, however not really documented anywhere how to implement... 这是在框中的文档中的某处提到的,但是在任何地方都没有真正记录如何实现...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM