Search code examples
javascripttypescriptgoogle-apigoogle-people-api

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


I am trying to list directory people from my google account.

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;
  }
}

However, the request fails with this error message:

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

I did not find any info in Google docs on how to correctly set scopes for People API in JS. How to set the scope in this case?


Solution

  • "Request had insufficient authentication scopes."

    Means that the currently authenticated user, the user you logged in with to create the access token. Has not granted you enough permissions to run the reuqest you are trying to run.

    You appear to be trying to run the people.listDirectoryPeople method which according to the documentation requires the following scope

    enter image description here

    As your appears to contain the following scope.

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

    The access token you are currently using was not created with that scope, you need to run your application again and force it to request access of the user again and request that scope.

    Either reset the cookies, or have the user forcefully remove the applications access via Permissions on their google developer account. How you do this will be up to you. But you need a new access token with the proper scope to use that method.

    people.get me works

    People.get works because it uses different set of scopes any off the following will work.

    enter image description here

    But which means you could be using https://www.googleapis.com/auth/userinfo.profile and people.get will work but people.listDirectoryPeople will not work because you do not have sufficient permissions, you need https://www.googleapis.com/auth/directory.readonly.