Google-api-nodejs-client:使用服务帐户调用目录 api 返回无效输入



我创建了一个服务帐户,并启用了全网域范围的委派。我已启用管理员 sdk 目录 api。我遵循列出所有用户的基本示例。在创建服务帐户时,我下载了一个文件。我从本文档中了解到,我需要将凭据文件传递给auth客户端。但是官方示例没有描述如何将文件实际传递给authClient。我尝试创建这样的请求:

const credentials = await JSON.parse(fs.readFileSync("cred.json"));
const auth = new google.auth.GoogleAuth({
credentials: credentials,
scopes: ["https://www.googleapis.com/auth/admin.directory.user"],
});
const authClient = await auth.getClient();
const { data } = await google
.admin({ version: "directory_v1", auth: authClient })
.users.list({
customer: "my_customer",
});

但是此请求返回Invalid Inputs.我似乎找不到关于这个主题的任何示例或解释。它还指出我必须模拟用户。但是文档没有显示将用户电子邮件放在哪里? 任何人都可以分享他们如何处理这个问题的经验吗?任何示例代码、文档或解释都将非常适用。

阅读您链接的最后一个示例,看起来您没有正确进行身份验证:

// Load client secrets from a local file.
const credentials = await JSON.parse(fs.readFileSync("cred.json"));
// Get authorization using your credentials.
authorize(credentials, listUsers);

/**
* Create an OAuth2 client with the given credentials, and then execute the
* given callback function.
*
* @param {Object} credentials The authorization client credentials.
* @param {function} callback The callback to call with the authorized client.
*/
function authorize(credentials, callback) {
const {client_secret, client_id, redirect_uris} = credentials.installed;
const oauth2Client = new google.auth.OAuth2(
client_id, client_secret, redirect_uris[0]);
return getNewToken(oauth2Client, callback);
}
/**
* Get new token after prompting for user authorization, and then
* execute the given callback with the authorized OAuth2 client.
*
* @param {google.auth.OAuth2} oauth2Client The OAuth2 client to get token for.
* @param {getEventsCallback} callback The callback to call with the authorized
*     client.
*/
function getNewToken(oauth2Client, callback) {
const authUrl = oauth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES,
});
console.log('Authorize this app by visiting this url:', authUrl);
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
rl.question('Enter the code from that page here: ', (code) => {
rl.close();
oauth2Client.getToken(code, (err, token) => {
if (err) return console.error('Error retrieving access token', err);
oauth2Client.credentials = token;
callback(oauth2Client);
});
});
}

/**
* Lists users in the domain.
*
* @param {google.auth.OAuth2} auth An authorized OAuth2 client.
*/
async function listUsers(auth) {
const service = google.admin({version: 'directory_v1', auth});
const {data} = await service.users.list({
customer: 'my_customer'
});
}

正如您在函数中看到的那样getNewToken您实际上通过浏览器与用户一起登录。

我简化了官方示例给定页面的代码。使用此代码,每次启动应用程序时都需要通过浏览器登录,但是如果您查看官方示例,则有一种方法可以存储通过OAuth2收到的令牌,这样它就不会总是要求进行身份验证。

最新更新