繁体   English   中英

当多次调用Google表格时,API身份验证无法用于第二次调用:请求的身份验证范围不足

[英]When making multiple calls to google sheets API authentication doesn't work for second call: Request had insufficient authentication scopes

因此,基本上我在这里所做的是,出于我自己的目的,我劫持了Google表格api node.js快速入门指南。 这里的所有东西都可以正常工作,直到打到我的sheets.batchUpdate,然后一切都变得古怪。

如果我注释掉电子表格sheets.batchUpdate中的“身份验证”初始化, The API returned an error: Error: The request does not have valid authentication credentials.收到错误消息: The API returned an error: Error: The request does not have valid authentication credentials.

如果我注释掉电子表格sheets.batchUpdate中的“身份验证”初始化, The API returned an error: Error: Request had insufficient authentication scopes.收到错误消息: The API returned an error: Error: Request had insufficient authentication scopes.

我要使用这些调用进行的所有操作都是从工作表中获取一些数据,然后在此之后删除行,但我无法弄清此身份验证问题。

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.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM