【问题标题】:Gmail API service account request- Precondition check failedGmail API 服务帐户请求 - 前提条件检查失败
【发布时间】:2020-11-28 15:17:36
【问题描述】:

我第一次尝试使用 google API,当我尝试向 gmail API 发出请求时,我收到“前提条件检查失败”错误。我正在使用服务帐户授权,而不是 Oauth2 用户同意。我尝试过的事情:

  1. 为服务帐户授权“域范围委派”。
  2. 确保 APP 在 G Suite 帐户中受信任。
  3. 确保服务帐户角色是“所有者”
  4. 在 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_CREDENTIALS env

标签: node.js google-api gmail


【解决方案1】:

在暗网上搜索永恒之后,我找到了一个指向 github issue 的链接,该链接描述了如何使用 JWT auth 进行身份验证作为服务。

这是我试图完成的工作版本:

const path = require('path');
const {google} = require('googleapis');

async getMessageList(userId, qty) {

  const JWT = google.auth.JWT;
  const authClient = new JWT({
    keyFile: path.resolve(__dirname, 'google-key.json'),
    scopes: ['https://www.googleapis.com/auth/gmail.readonly'],
    subject: 'admin@example.com' // google admin email address to impersonate
  });

  await authClient.authorize(); // once authorized, can do whatever you want

  const gmail = google.gmail({
    auth: authClient,
    version: 'v1'
  });

  const response = await gmail.users.messages.list({
    includeSpamTrash: false,
    maxResults: qty,
    q: "",
    userId: userId
  });

  // the data object includes a "messages" array of message data
  return response.data;

}

【讨论】:

  • 对我来说,await authClient.authorize(); 不是必需的。我与您的用例的唯一区别是我使用 https://mail.google.com/ 作为范围。
猜你喜欢
  • 1970-01-01
  • 2020-10-31
  • 2022-11-09
  • 2018-08-12
  • 2017-01-08
  • 2014-09-13
  • 2020-09-23
  • 1970-01-01
  • 2016-12-19
相关资源
最近更新 更多