如何设置正确的范围以调用 JavaScript 中的 Google 人 API?

How do I set the correct scope to call the Google People API in JavaScript?

我正在尝试列出我的 google 帐户中的目录人员。

export class People {
  private auth: Auth.OAuth2Client;
  private initialized: boolean = false;
  private accessToken: string;

  constructor(private readonly clientEmail: string, private readonly pKey: string) {}

  public async people() {
    await this.initialize();
    const googlePeople = google.people({ version: 'v1', auth: this.auth });
    const people = await googlePeople.people.listDirectoryPeople();
    return people.data;
  }

  public async setToken(accessToken: string) {
    this.accessToken = accessToken;
  }

  private async initialize() {
    if (this.initialized) {
      return;
    }
    this.auth = new google.auth.OAuth2({
      clientId: 'xxx',
      clientSecret: 'zzz',
      redirectUri: 'http://localhost:3000/people',
    });
    this.auth.setCredentials({
      access_token: this.accessToken,
      scope: 'https://www.googleapis.com/auth/directory.readonly',
    });

    this.initialized = true;
  }
}

但是,请求失败并显示此错误消息:

error: {
  code: 403,
  message: "Request had insufficient authentication scopes.",
  errors: [
    {
      message: "Insufficient Permission",
      domain: "global",
      reason: "insufficientPermissions"
    }
  ],
  status: "PERMISSION_DENIED"
}

我在 Google 文档中没有找到任何关于如何在 JS 中正确设置 People API 范围的信息。在这种情况下如何设置范围?

"Request had insufficient authentication scopes."

表示当前经过身份验证的用户,即您登录时用来创建访问令牌的用户。没有授予您足够的权限 运行 您正在尝试 运行.

您似乎正在尝试 运行 people.listDirectoryPeople 方法,根据文档,该方法需要以下范围

因为您似乎包含以下范围。

scope: 'https://www.googleapis.com/auth/directory.readonly',

您当前使用的访问令牌不是在该范围内创建的,您需要再次 运行 您的应用程序并强制它再次请求用户访问并请求该范围。

要么重置 cookie,要么让用户通过 Permissions 在其 google 开发者帐户上强制删除应用程序访问权限。你如何做到这一点将取决于你。但是您需要一个具有适当范围的新访问令牌才能使用该方法。

people.get我工作

People.get 有效,因为它使用不同的范围集,以下任何一项都有效。

但这意味着您可以使用 https://www.googleapis.com/auth/userinfo.profile 并且 people.get 可以,但是 people.listDirectoryPeople 将不起作用,因为您没有足够的权限,您需要 https://www.googleapis.com/auth/directory.readonly