Google 令牌已过期或撤销

Google Token has been expired or revoked

我正在尝试实现一个应用程序来提醒用户即将到来的 google 日历事件。我已成功创建 google OAuth 令牌,我的应用程序运行良好。但突然我得到这个错误“错误:'invalid_grant',error_description:'Token has been expired or revoked.'”。 这是我的代码:

const TOKEN_PATH = 'token.json';

const OAuth2 = google.auth.OAuth2;

const googleConfig = {
  clientId: 'xxxxxxxxxxx', 
  clientSecret: 'xxxxxxxxxxxxxxxx', 
  redirect: 'xxxxxxxxxxxxxxx/landingPage' 
};

function createConnection() {
  return new OAuth2(
    googleConfig.clientId,
    googleConfig.clientSecret,
    googleConfig.redirect
  );
}

const defaultScope = [
   'https://www.googleapis.com/auth/calendar.readonly'
];

function getConnectionUrl(auth) {

  return auth.generateAuthUrl({
    access_type: 'offline',
    prompt: 'consent', // access type and approval prompt will force a new refresh token to be made each time signs in
    scope: defaultScope

  });
}

function urlGoogle() {
  const auth = createConnection(); // this is from previous step
  const url = getConnectionUrl(auth);
  return url;
}

app.get('/', function (req, res) {
    const url = urlGoogle()
    return res.render("index", { loginLink: url });
});

 app.get('/landingPage', (req, res) => {
    const OAuth = createConnection()
    function getNewToken(OAuth) {
      OAuth.getToken(req.query.code, (err, token) => {
        if (err) return console.error('Error retrieving access token', err);
        OAuth.setCredentials(token);
        fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
          if (err) return console.error(err);
          console.log('Token stored to', TOKEN_PATH);
          callHFunction(OAuth)
        });
      });
      }
      // Check if we have previously stored a token.
    fs.readFile(TOKEN_PATH, (err, token) => {
      if (err) return getNewToken(OAuth);
      OAuth.setCredentials(JSON.parse(token));
      console.log(OAuth.credentials)
      callHFunction(OAuth)
    });
    res.sendFile(path.join(__dirname, "./landingPage.html"));
  });

知道如何解决这个问题吗?

最常见的原因

error: 'invalid_grant'

  • 用户撤销了您的访问权限。
  • 您已达到未完成刷新令牌的最大数量 (50) 请确保始终存储最新的。
  • 您的应用仍处于测试阶段。刷新令牌将在 7 - 14 天后过期。

如果您遇到此错误,最好通过提示用户再次授权您的应用程序来确保您的应用程序能够处理它。