如何使用JWT通过NodeJS客户端库访问Google Directory(Admin SDK)? [英] How do I use JWT to access Google Directory (Admin SDK) using NodeJS client libraries?

查看:104
本文介绍了如何使用JWT通过NodeJS客户端库访问Google Directory(Admin SDK)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to make a server application that will add/remove users to my domain's groups. Note that it will not have any interaction with users, it is server-to-server application.

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

I registered my application in the Google API Console, downloaded the key and transformed it to .pem by issuing

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

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

Then I've been to the Domain Administration, Security -> Advanced Settings -> Authentication -> Manage OAuth Client access. There I added a record in Authorized API clients. I used the Client ID I got from the Service Account in Console and used scope:

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

我使用

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授权我的应用程序?

What am I missing? How do I authorize my application with the Admin SDK?

推荐答案

1)确保将域范围的权限委派给您的服务帐户.

1) Make sure you delegate domain wide authority to your service account.

2)服务帐户必须模拟可访问Admin SDK Directory API的人.

2) Service Accounts must impersonate someone with access to the 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'],
    account_with_Admin_SDK_access_to_impersonate@example.com
);

文档的此部分详细介绍了这两个方面: 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆