javascript - 多次调用 google 表格时,API 身份验证不适用于第二次调用 : Request had insufficient authentication scopes

标签 javascript node.js authentication google-sheets-api

基本上,我在这里所做的就是出于我自己的目的劫持了 google sheets api node.js 快速入门指南。这里的一切都很好,直到它到达我的 spreadsheets.batchUpdate,然后一切都变得古怪。

如果我注释掉 spreadsheets.batchUpdate 中的“auth”初始化,我会收到错误消息:API 返回错误:错误:请求没有有效的身份验证凭据。

如果我在 spreadsheets.batchUpdate 中注释掉“auth”初始化,我会收到错误消息:API 返回错误:错误:请求的身份验证范围不足。

我尝试对这些调用做的只是从工作表中获取一些数据,然后删除之后的行,但我无法弄清楚这个身份验证问题。

var fs = require('fs');
var updateDB = require('./updateDB.js');
var readline = require('readline');
var google = require('googleapis');
var googleAuth = require('google-auth-library');
var splitData;


// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/sheets.googleapis.com-nodejs-quickstart.json
var SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly'];
var TOKEN_DIR = (process.env.HOME || process.env.HOMEPATH ||
    process.env.USERPROFILE) + '/.credentials/';
var TOKEN_PATH = TOKEN_DIR + 'sheets.googleapis.com-nodejs-quickstart.json';
var array = [];

var run = {
  runQuickstart : function() {
    // Load client secrets from a local file.
    fs.readFile('client_secret.json', function processClientSecrets(err, content) {
      if (err) {
        console.log('Error loading client secret file: ' + err);
        return;
      }
      // Authorize a client with the loaded credentials, then call the
      // Google Sheets API.
      authorize(JSON.parse(content), listMajors);
    });
  }
}

/**
 * Create an OAuth2 client with the given credentials, and then execute the
 * given callback function.
 *
 * @param {Object} credentials The authorization client credentials.
 * @param {function} callback The callback to call with the authorized client.
 */
function authorize(credentials, callback) {
  var clientSecret = credentials.installed.client_secret;
  var clientId = credentials.installed.client_id;
  var redirectUrl = credentials.installed.redirect_uris[0];
  var auth = new googleAuth();
  var oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);

  // Check if we have previously stored a token.
  fs.readFile(TOKEN_PATH, function(err, token) {
    if (err) {
      getNewToken(oauth2Client, callback);
    } else {
      oauth2Client.credentials = JSON.parse(token);
      callback(oauth2Client);
    }
  });
}

/**
 * Get and store new token after prompting for user authorization, and then
 * execute the given callback with the authorized OAuth2 client.
 *
 * @param {google.auth.OAuth2} oauth2Client The OAuth2 client to get token for.
 * @param {getEventsCallback} callback The callback to call with the authorized
 *     client.
 */
function getNewToken(oauth2Client, callback) {
  var authUrl = oauth2Client.generateAuthUrl({
    access_type: 'offline',
    scope: SCOPES
  });
  console.log('Authorize this app by visiting this url: ', authUrl);
  var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
  });
  rl.question('Enter the code from that page here: ', function(code) {
    rl.close();
    oauth2Client.getToken(code, function(err, token) {
      if (err) {
        console.log('Error while trying to retrieve access token', err);
        return;
      }
      oauth2Client.credentials = token;
      storeToken(token);
      callback(oauth2Client);
    });
  });
}

/**
 * Store token to disk be used in later program executions.
 *
 * @param {Object} token The token to store to disk.
 */
function storeToken(token) {
  try {
    fs.mkdirSync(TOKEN_DIR);
  } catch (err) {
    if (err.code != 'EEXIST') {
      throw err;
    }
  }
  fs.writeFile(TOKEN_PATH, JSON.stringify(token));
  console.log('Token stored to ' + TOKEN_PATH);
}

/**
 * Print the names and majors of students in a sample spreadsheet:
 * https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
 */
function listMajors(auth) {
  var sheets = google.sheets('v4');
  sheets.spreadsheets.values.get({
    auth: auth,
    spreadsheetId: '1EV8S8AaAmxF3vP0F6RWxKIUlvF6uFEmsrOFWA1oNBYI',
    range: 'Form Responses 1!A3:X3',
  }, function(err, response) {
    if (err) {
      console.log('The API returned an error: ' + err);
      return;
    }
    var rows = response.values;
    //splitData = rows.split(',');
    updateDB.inputFormToDB.apply(this, rows);
    if (rows.length == 0) {
      console.log('No data found.');
    } else {
      console.log('Form Responses');
      for (var i = 0; i < rows.length; i++) {
        var row = rows[i];
        // Print columns A and E, which correspond to indices 0 and 4.
        console.log('%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s', row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7], row[8], row[9],row[10], row[11], row[12], row[13], row[14], row[15], row[16], row[17], row[18], row[19], row[20], row[21], row[22], row[23]);
      }


      var spreadsheetId = '1EV8S8AaAmxF3vP0F6RWxKIUlvF6uFEmsrOFWA1oNBYI';
      var requests = [];
      requests.push({
        "deleteDimension": {
          "range": {
            "sheetId": spreadsheetId,
            "dimension": "ROWS",
            "startIndex": 0,
            "endIndex": 3
          }
        }
      });
      var batchUpdateRequest = {requests: requests}
      var test = auth;
      sheets.spreadsheets.batchUpdate({
        // auth: test,
        spreadsheetId: spreadsheetId,
        resource: batchUpdateRequest
      }, function(err, response) {
        if (err) {
          console.log('The API returned an error: ' + err);
          return;
        }
      });

    }
  });
}

module.exports = run;

最佳答案

https://www.googleapis.com/auth/spreadsheets.readonly 将为您提供阅读权限。 您需要使用 https://www.googleapis.com/auth/spreadsheets 范围来更新工作表。

https://www.googleapis.com/auth/spreadsheets.readonly

Allows read-only access to the user's sheets and their properties.

https://www.googleapis.com/auth/spreadsheets

Allows read/write access to the user's sheets and their properties.

关于javascript - 多次调用 google 表格时,API 身份验证不适用于第二次调用 : Request had insufficient authentication scopes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40364985/

相关文章:

node.js - MongoDB - $nin 聚合运算符无效

Facebook 身份验证无需重定向?

javascript - "progressive"网站加载中

javascript - NestJs 在 npm start 上加载环境变量

javascript - 通过 php 上传 Angular JS 文件——未定义索引 :

python - 如何使用 Tornado 网络服务器进行点对点视频聊天

针对本地 SASL 的 Java 身份验证

.net - .Net 2.0 Web 服务中的 SSPI 连接

javascript - 切换 Dojo dijit 的显示

javascript - 有没有任何 UpToDate 可能的方法通过 Javascript 将 PDF/DocX 转换为文本