无法获取Google API的刷新令牌。节点js

时间:2018-10-02 00:32:06

标签: node.js oauth-2.0 google-api

我有一个可通过Google API远程运行的Apps脚本脚本。当我转到链接时,它为我提供了获取访问令牌的代码,它表示请求的文件不存在。但是,代码仍然在url中,这给了我访问令牌,但没有刷新令牌。

我尝试添加'access_type:offline'和'approval_prompt:force',但是这些都没有改变。这是代码:

var { google } = require('googleapis');
var fs = require('fs');
var async = require('async');
const readline = require('readline');




// If modifying these scopes, delete token.json.
const SCOPES = [
  "https://www.googleapis.com/auth/drive",
  "https://www.googleapis.com/auth/script.projects",
  "https://www.googleapis.com/auth/spreadsheets"

];
const TOKEN_PATH = 'token.json';

// Load client secrets from a local file.
fs.readFile('./credentials.json', (err, content) => {
  if (err) return console.log('Error loading client secret file:', err);
  // Authorize a client with credentials, then call the Google Apps Script API.
  authorize(JSON.parse(content), callScriptFunction);
});

/**
 * 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) {
  //   const {client_secret, client_id, redirect_uris} = credentials.installed;
  const oAuth2Client = new google.auth.OAuth2("294862899955-bb0929ato2qem8cqllggrpuqpqit191v.apps.googleusercontent.com", "Ds4-q0G3QZog4UamQrc3HFrW", "https://script.google.com/oauthcallback");

  // Check if we have previously stored a token.
  fs.readFile(TOKEN_PATH, (err, token) => {
    if (err) return getAccessToken(oAuth2Client, callback);
    oAuth2Client.setCredentials(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 for the authorized client.
 */
function getAccessToken(oAuth2Client, callback) {
  const authUrl = oAuth2Client.generateAuthUrl({
    access_type: 'offline',
    scope: SCOPES,
  });
  console.log('Authorize this app by visiting this url:', authUrl);
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
  });
  rl.question('Enter the code from that page here: ', (code) => {
    rl.close();
    oAuth2Client.getToken(code, (err, token) => {
      if (err) return console.error('Error retrieving access token', err);
      oAuth2Client.setCredentials(token);
      // Store the token to disk for later program executions
      fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
        if (err) console.error(err);
        console.log('Token stored to', TOKEN_PATH);
      });
      callback(oAuth2Client);
    });
  });
}

function callScriptFunction(auth) {
  var scriptId = "MwnuiFwldt-0ZLyLnoi0Q5kfoO49Cn6ao";
  var script = google.script('v1');

  script.scripts.run({
    auth: auth,
    resource: {
      function: 'automateSheet',
      parameters: [
        process.argv[2],
        process.argv[3],
        process.argv[4],
        process.argv[5],
        process.argv[6],
        process.argv[7],
        process.argv[8],
      ]
    },
    scriptId: scriptId,
    devMode: true
  }, function (err, resp) {
    if (err) {
      console.log(err);
    }
    else {
      var r = resp.data;
      if ("error" in r) {
        console.log("Error: %o", r.error);
      } else {
        console.log("Result: %o", r.response.result);
      }
    }
  });
}

当我同意允许该应用访问我的帐户时,这是Google给我的页面:enter image description here

2 个答案:

答案 0 :(得分:0)

我在这里找到了答案:

Not receiving Google OAuth refresh token

那家伙说去https://myaccount.google.com/u/2/permissions?pli=1&pageId=none

然后撤消您的应用权限。它为我工作。因为每次第一次之后刷新令牌都不会出现

答案 1 :(得分:0)

我认为有两个问题。一,看起来您的授权重定向 URI 设置不正确。它需要设置为您服务器上的一个页面,该页面在用户授权后侦听代码 URL 参数。您可以在 Google Cloud 控制台中的 API > Credentials > 0Auth Client Settings > Authorized redirect URIs 下进行设置。

其次,我遇到了一个问题,有时我无法获得刷新令牌。结果我不得不将 prompt: 'consent' 添加到 generateAuthUrl 请求以强制它始终返回刷新令牌,方法是始终引导用户完成完整的授权流程(而不是跳过最近通过身份验证的步骤)。所以你的功能是:

const authUrl = oAuth2Client.generateAuthUrl({
    access_type: 'offline',
    scope: SCOPES,
    prompt: 'consent',
});

希望有所帮助。供参考:https://github.com/googleapis/google-api-nodejs-client/issues/750#issuecomment-368873635