我正在尝试创建一个基于 NodeJS 的云函数,它使用域范围的委托访问来使用 API 方法 gmail.users.settings.delegates.list。
我正在寻找不使用服务帐户 JSON 密钥的解决方案,我想改用默认凭据。
我使用这个 launch.json 文件配置我的本地环境来模拟云功能环境
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Launch usersOnBehalfCheck",
"skipFiles": [
"<node_internals>/**"
],
"env": {
"GCP_PROJECT":"projectId",
"GOOGLE_APPLICATION_CREDENTIALS": "pathToJsonFile.json"
},
"program": "${workspaceFolder}/index.js"
}
]
}
将 env 变量打印GOOGLE_APPLICATION_CREDENTIALS
到 GCF 中似乎这个变量根本不存在,但我不明白如何更好地模拟 GCF env
谈到auth对象,我发现了两种方法:
第一的:
const gmailDWDAuth = new GoogleAuth({ clientOptions: { subject: inputData.userPrimaryEmail }, scopes: ['https://www.googleapis.com/auth/gmail.settings.basic'] });
console.info({ gmailDWDAuth: gmailDWDAuth }, null, 2);
return gmail.users.settings.delegates.list({ userId: 'me', auth: gmailDWDAuth })
第二:
const gmailDWDAuth = await google.auth.getClient({ clientOptions: { subject: inputData.userPrimaryEmail }, scopes: ['https://www.googleapis.com/auth/gmail.settings.basic'] });
console.info({ gmailDWDAuth: gmailDWDAuth }, null, 2);
return gmail.users.settings.delegates.list({ userId: 'me', auth: gmailDWDAuth })
inputData.userPrimaryEmail
包含与服务帐号在同一组织中的有效 GSuite 帐号。
Bad Request
当我将 GCF 发布到 GCP 时,这两种方式在本地都可以正常工作,但会因错误而停止工作。
谁能帮忙?
编辑
几个小时后,我发现这篇文章谈到了它
我按照他的指示修改了我的代码
第三:
const DWDAuth = await google.auth.getClient({ scopes: ['https://www.googleapis.com/auth/gmail.settings.basic'] });
DWDAuth.subject = inputData.userPrimaryEmail;
console.info(util.inspect({ DWDAuth: DWDAuth }));
return gmail.users.settings.delegates.list({ userId: inputData.userPrimaryEmail, auth: DWDAuth })
第四:
const DWDAuth = new GoogleAuth({ scopes: ['https://www.googleapis.com/auth/gmail.settings.basic'] });
const DWDAuthClient = await DWDAuth.getClient();
DWDAuthClient.subject = inputData.userPrimaryEmail;
console.info(util.inspect({ DWDAuthClient: DWDAuthClient }));
return gmail.users.settings.delegates.list({ userId: inputData.userPrimaryEmail, auth: DWDAuthClient })
和以前一样,所有这些在本地都可以正常工作,但是我对 GCF 提出了错误的请求