首页 > 解决方案 > 403 "Insufficient authentication scopes" with Google Sheets API and Service Account

问题描述

I can't for the life of me figure out why this isn't working. I feel like I've done everything comparable to what's done in this tutorial, but it's not working.

I have done the following:

  1. Created a project with the Google Sheets API enabled.
  2. Created a Service Account under the Credentials section of my project.
  3. Downloaded the JSON configuration file for the Service Account.
  4. Saved the private key (-----BEGIN PRIVATE KEY----...., all on one line), the client email, and the project ID to my environment variables.

My code looks like so:

import GoogleAPIs from 'googleapis';
import googleAuth from 'google-auth-library';

export default class GoogleSheetsAPI {

  connect() {
    return new Promise(async resolve => {
      const client = new googleAuth.JWT(
        process.env.GOOGLE_CLIENT_EMAIL,
        null,
        process.env.GOOGLE_PRIVATE_KEY.replace(/\\n/g, '\n'),
        ['https://www.googleapis.com/auth/spreadsheets.readonly']
      );
      const url = 'https://www.googleapis.com/dns/v1/projects/' + process.env.GOOGLE_PROJECT_ID;
      client.request({url})
        .then(res => console.log(res.data))
        .catch(err => console.error(err));
    });
  }
  ...
}

I've verified that the values are being loaded correctly from the environment variables.

This is the response I get after calling connect() on a new instance of GoogleSheetsAPI:

{ Error: Request had insufficient authentication scopes.
    at Gaxios.request (<project_folder>/node_modules/gaxios/build/src/gaxios.js:70:23)
    at process.internalTickCallback (internal/process/next_tick.js:77:7)
  response:
   { config:
      { url: 'https://www.googleapis.com/dns/v1/projects/<redacted but good>',
        headers:
         { Authorization:
            'Bearer <redacted but looks reasonable>',
           'User-Agent': 'google-api-nodejs-client/5.1.1',
           Accept: 'application/json' },
        params: [Object: null prototype] {},
        paramsSerializer: [Function: paramsSerializer],
        validateStatus: [Function: validateStatus],
        responseType: 'json',
        method: 'GET' },
     data:
      { error:
         { code: 403,
           message: 'Request had insufficient authentication scopes.',
           errors:
            [ { message: 'Request had insufficient authentication scopes.',
                domain: 'global',
                reason: 'forbidden' } ],
           status: 'PERMISSION_DENIED' } },
  ...

Surely it's something simple. Any ideas? Thanks!

标签: node.jsgoogle-sheets-apigoogle-auth-library

解决方案


推荐阅读