如何使用 NodeJS 客户端库使用 JWT 访问 Google Directory (Admin SDK)?

2024-04-07

我正在尝试创建一个服务器应用程序,将用户添加/删除到我的域的组中。请注意,它不会与用户进行任何交互,它是服务器到服务器的应用程序。

我在 Google API 控制台中注册了我的应用程序,下载了密钥并通过发出将其转换为 .pem

openssl pkcs12 -in my_google_key.p12 -out my_google_key.pem -nocerts -nodes

然后我进入域管理,安全 -> 高级设置 -> 身份验证 -> 管理 OAuth 客户端访问。我在授权 API 客户端中添加了一条记录。我使用了从控制台中的服务帐户获得的客户端 ID 并使用了范围:

https://www.googleapis.com/auth/admin.directory.group.

我为nodejs安装了googleapis,使用

npm install googleapis

这是我的代码:

var googleapis = require('googleapis');

var SERVICE_ACCOUNT_EMAIL = 'My Service Account E-mail Address';
var SERVICE_ACCOUNT_KEY_FILE = 'my_google_key.pem'; // The .pem file is at the root of my application

var jwt = new googleapis.auth.JWT(
    SERVICE_ACCOUNT_EMAIL,
    SERVICE_ACCOUNT_KEY_FILE,
    null,
    ['https://www.googleapis.com/auth/admin.directory.group']
);

var client;

googleapis
.discover('admin', 'directory_v1')
.execute(function(err, data) {
    client = data;

    jwt.authorize(function(err, result) {
        console.log(jwt);
        client.admin.groups.list({
            "customer": "my_customer", // This is actually "my_customer"
            "domain": "domain.com" // The domain name I administer
        })
        .withAuthClient(jwt)
        .execute(function(err, result) {
            console.log(err);
            console.log(result);
        });
    });
});

运行这段代码的结果是:

{ errors: 
    [ { domain: 'global',
        reason: 'forbidden',
        message: 'Not Authorized to access this resource/api' } ],
    code: 403,
    message: 'Not Authorized to access this resource/api' }

我缺少什么?如何使用 Admin SDK 授权我的应用程序?


1) 确保将域范围内的权限委托给您的服务帐户。

2) 服务帐户必须模拟有权访问 Admin SDK Directory API 的人员。

初始化时包含它:

var jwt = new googleapis.auth.JWT(
    SERVICE_ACCOUNT_EMAIL,
    SERVICE_ACCOUNT_KEY_FILE,
    null,
    ['https://www.googleapis.com/auth/admin.directory.group'],
    [email protected] /cdn-cgi/l/email-protection
);

文档的这一部分详细解释了这两个问题: https://developers.google.com/admin-sdk/directory/v1/guides/delegation#delegate_domain-wide_authority_to_your_service_account https://developers.google.com/admin-sdk/directory/v1/guides/delegation#delegate_domain-wide_authority_to_your_service_account

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 NodeJS 客户端库使用 JWT 访问 Google Directory (Admin SDK)? 的相关文章

随机推荐