繁体   English   中英

Nodemailer 中的 Google 刷新令牌 7 天有效期

[英]Google refresh token 7-day expiration period in Nodemailer

谷歌上个月在他们的邮件服务上关闭了“不太安全的应用程序”功能。 因此,我不能只使用 email 和密码来使用 Nodemailer。 我被迫使用 Google OAuth 设置 Nodemailer。 但是,刷新令牌每周都会过期。 我应该怎么办?

这是我的转运代码。

const transporter = nodemailer.createTransport({
            service: 'gmail',
            auth: {
                type: 'OAuth2',
                user: process.env.GA_MAIL,
                accessToken,
                clientId: process.env.GA_CLIENT_ID,
                clientSecret: process.env.GA_CLIENT_SECRET,
                refreshToken: process.env.GA_REFRESH_TOKEN,
            },
});

这是措辞更好的问题:

这是文件 token.js :

const { google } = require('googleapis');
const path = require('path');
const fs = require('fs');
const credentials = require('./email.json');

// Replace with the code you received from Google
const code = "";
const { client_secret, client_id, redirect_uris } = credentials.installed;
const oAuth2Client = new google.auth.OAuth2(client_id, client_secret, redirect_uris[0]);

oAuth2Client.getToken(code).then(({ tokens }) => {
  const tokenPath = path.join(__dirname, 'token.json');
  fs.writeFileSync(tokenPath, JSON.stringify(tokens));
  console.log('Access token and refresh token stored to token.json');
});

运行 token.js 文件时,会创建一个名为 token.json 的文件,其中包含一些访问令牌:

{"access_token":"","refresh_token":"","scope":"https://www.googleapis.com/auth/gmail.send","token_type":"Bearer","expiry_date":1656595108942}

但 7 天后 access_token 过期。

我想出的一个解决方案,虽然它未经测试,是在 .catch() 块内调用令牌刷新,如下所示:

主.js:

//...
const refreshToken = require("./refresh_token.js");
//...
}).catch((err) => {
    reply(interaction,"Error, Refreshing token.. Please try again");
    console.error(err);
    refreshToken();
    return;
});
//...

refresh_token.js :

const { google } = require('googleapis');
const path = require('path');
const fs = require('fs');
const credentials = require('./email.json');
const token = require("./token.json");

module.exports = () => {
  const code = token.refresh_token;
  const { client_secret, client_id, redirect_uris } = credentials.installed;
  const oAuth2Client = new google.auth.OAuth2(client_id, client_secret, redirect_uris[0]);

  oAuth2Client.getToken(code).then(({ tokens }) => {
    const tokenPath = path.join(__dirname, 'token.json');
    fs.writeFileSync(tokenPath, JSON.stringify(tokens));
    console.log('Access token and refresh token stored to token.json');
  });
}

我将它放在 catch 语句中的原因是,当令牌未过期时,我们在尝试运行 oAuth2Client.getToken(token.refresh_token) 时收到 invalid_grant 错误

^^ 这还没有经过测试^^

如果 refresh_token 也过期了,那么我不知道该怎么做,请帮忙

在 Google Developer Console 中将测试模式设置为生产模式将防止刷新令牌过期。

暂无
暂无

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

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