【问题标题】:can't get refresh token for google api. Node js无法获取 google api 的刷新令牌。节点js
【发布时间】:2021-02-10 22:43:22
【问题描述】:

我有一个 Apps Script 脚本,我正在通过 Google 的 API 远程运行它。当我转到链接时,它为我提供了检索访问令牌的代码,它说请求的文件不存在。但是,无论如何,代码都在 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 为我提供的页面:

【问题讨论】:

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


    【解决方案1】:

    我在这里找到了答案:

    Not receiving Google OAuth refresh token

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

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

    【讨论】:

      【解决方案2】:

      我认为有两个问题正在发生。一,您的 Authorized redirect URI 似乎设置不正确。需要在你的服务器上设置一个页面,在用户授权后监听code 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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-02-15
        • 2020-10-08
        • 2021-06-12
        • 1970-01-01
        • 1970-01-01
        • 2012-10-26
        • 2021-09-04
        • 2016-10-13
        相关资源
        最近更新 更多