【发布时间】:2020-11-28 15:17:36
【问题描述】:
我第一次尝试使用 google API,当我尝试向 gmail API 发出请求时,我收到“前提条件检查失败”错误。我正在使用服务帐户授权,而不是 Oauth2 用户同意。我尝试过的事情:
- 为服务帐户授权“域范围委派”。
- 确保 APP 在 G Suite 帐户中受信任。
- 确保服务帐户角色是“所有者”
- 在 g 套件管理面板中为服务帐户的客户端 ID 启用了域范围的委派。
这是来自 Node 客户端库的改编 sample,但该示例未使用服务帐户身份验证,因此我无法直接使用该示例。
const path = require('path');
const {google} = require('googleapis');
const gmail = google.gmail('v1');
async function runSample() {
// Obtain user credentials to use for the request
const auth = new google.auth.GoogleAuth({
keyFile: path.resolve(__dirname, 'google-key.json'),
scopes: ['https://www.googleapis.com/auth/gmail.readonly'],
});
google.options({auth});
const res = await gmail.users.messages.list({userId: 'me'}); // have tried with my gsuite email address as well
console.log(res.data);
return res.data;
}
if (module === require.main) {
runSample().catch(console.error);
}
module.exports = runSample;
返回错误消息:Error: Precondition check failed.
【问题讨论】:
-
您不能使用“我”来检查服务帐户电子邮件。您需要将其委托给 gsuite 域上的用户。
-
@DaImTo 我也尝试使用我的用户 ID / 电子邮件而不是“我”并得到相同的结果。我启用了域范围的委派。您的评论是否仍然适用?
-
我遇到了一个非常相似的问题,JWT 解决方案也适用于 GoogleAuth 构造函数:
new GoogleAuth({ keyFile, scopes, clientOptions: { subject: 'emailToImpersonate' } })。keyFile可能会被删除以支持GOOGLE_APPLICATION_CREDENTIALSenv
标签: node.js google-api gmail