[英]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.