Google Calendar API和服务帐户权限错误

时间:2020-03-22 20:21:14

标签: node.js jwt google-calendar-api

我正在尝试将Google Calendar API集成到我的应用中。 到目前为止,我已经做到了:

  • 在Cloud Platform上创建了一个新项目
  • 已启用日历API
  • 添加了一个角色为“所有者”的新服务帐户
  • 生成的jwt.json
  • 该服务帐户在全域范围内获得许可
  • 与该服务帐户共享日历(修改权限)
  • 在GSuite中启用了组织外所有人修改事件的选项

现在,我在node.js上的代码如下:

const { JWT } = require('google-auth-library');

const client = new JWT(
    keys.client_email,
    null,
    keys.private_key,
    ['https://www.googleapis.com/auth/calendar']
);

const url = `https://dns.googleapis.com/dns/v1/projects/${keys.project_id}`;
const rest = await client.request({url});
console.log(rest);

我得到的错误是:

发送500(“服务器错误”)响应: 错误:权限不足

有人有什么想法吗?这令人沮丧。

1 个答案:

答案 0 :(得分:1)

该修改如何?

我认为在您的脚本中,端点和/或范围可能不正确。

模式1:

在这种模式下,将使用https://dns.googleapis.com/dns/v1/projects/${keys.project_id}的端点。

修改后的脚本:

const { JWT } = require("google-auth-library");
const keys = require("###");  // Please set the filename of credential file of the service account.

async function main() {
  const calendarId = "ip15lduoirvpitbgc4ppm777ag@group.calendar.google.com";
  const client = new JWT(keys.client_email, null, keys.private_key, [
    'https://www.googleapis.com/auth/cloud-platform'  // <--- Modified
  ]);
  const url = `https://dns.googleapis.com/dns/v1/projects/${keys.project_id}`;
  const res = await client.request({ url });
  console.log(res.data);
}

main().catch(console.error);
  • 在这种情况下,需要在API控制台上启用Cloud DNS API。并且需要支付。请注意这一点。
    • 我认为您的Insufficient Permission错误消息的原因可能是这样。

模式2:

在此模式下,作为示例情况,从与服务帐户共享的日历中检索事件列表。如果日历可以与服务帐户一起使用,则返回事件列表。这样,我认为您可以确认该脚本是否有效。

修改后的脚本:

const { JWT } = require("google-auth-library");
const keys = require("###");  // Please set the filename of credential file of the service account.

async function main() {
  const calendarId = "###";  // Please set the calendar ID.

  const client = new JWT(keys.client_email, null, keys.private_key, [
    "https://www.googleapis.com/auth/calendar"
  ]);
  const url = `https://www.googleapis.com/calendar/v3/calendars/${calendarId}/events`;  // <--- Modified
  const res = await client.request({ url });
  console.log(res.data);
}

main().catch(console.error);

注意:

  • 此修改后的脚本假定您正在使用最新版本的google-auth-library-nodejs

参考:

如果我误解了您的问题,而这不是您想要的方向,我深表歉意。