Node.js Gmail Api访问令牌在过期后不会更改-但访问仍然有效
我正在开发一个基本的应用程序,它只需从特定的gmail帐户(比如fakeEmail@gmail.com) . 在第一次运行时,该应用程序被授予读取电子邮件的权限fakeEmail@gmail.com . 并且访问令牌、到期日(1小时)和刷新令牌等保存到“token.json”文件中 即使在访问令牌过期之后的后续运行中,我也不会看到刷新令牌请求,但应用程序能够从中获取和读取电子邮件fakeEmail@gmail.com. 该应用程序作为“node app.js”从命令行运行,它获取带有特定标签的电子邮件,并在控制台上打印电子邮件内容 每次运行应用程序时,第一个调用的方法是authorize()。只有在第一次运行时才调用getNewToken(),当用户fakeEmail@gmail.com授予应用程序阅读其电子邮件的权限 以下是此简单应用程序的相关代码:Node.js Gmail Api访问令牌在过期后不会更改-但访问仍然有效,node.js,google-api,gmail-api,Node.js,Google Api,Gmail Api,我正在开发一个基本的应用程序,它只需从特定的gmail帐户(比如fakeEmail@gmail.com) . 在第一次运行时,该应用程序被授予读取电子邮件的权限fakeEmail@gmail.com . 并且访问令牌、到期日(1小时)和刷新令牌等保存到“token.json”文件中 即使在访问令牌过期之后的后续运行中,我也不会看到刷新令牌请求,但应用程序能够从中获取和读取电子邮件fakeEmail@gmail.com. 该应用程序作为“node app.js”从命令行运行,它获取带有特定标签的电
const SCOPES = ['https://www.googleapis.com/auth/gmail.readonly'];
const TOKEN_PATH = 'token.json';
const fs = require('fs');
const readline = require('readline');
const {google} = require('googleapis');
function authorize(credentials, callback) {
const {client_secret, client_id, redirect_uris} = credentials.installed;
const oAuth2Client = new google.auth.OAuth2(client_id, client_secret, redirect_uris[0]);
// Check if we have previously stored a token.
fs.readFile(TOKEN_PATH, (err, token) => {
if (err) return getNewToken(oAuth2Client, callback);
oAuth2Client.setCredentials(JSON.parse(token));
callback(oAuth2Client);
});
}
function getNewToken(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) return console.error(err);
console.log('Token stored to', TOKEN_PATH);
});
callback(oAuth2Client);
});
});
}
function startApp(){
fs.readFile('gmailCredentials.json', (err, content) => {
if (err)
return console.log('Error loading client secret file:', err);
authorize(JSON.parse(content), function(auth){
checkForMailsWithLabel(auth, strLabel, function(err, res){
console.log("auth holds: " + util.inspect(auth) );
// this prints the same accessToken and expiration as the one we have in 'token.json'
// Even though the token is expired, the app is still able to read the emails
});
});
});
}
您在这里看到的代码几乎与github上的示例完全相同:
如果有关系的话,我还没有完成与谷歌对这个应用程序的验证过程。由于我正在使用自己的电子邮件帐户进行测试,因此授予权限时出现的不可信警告目前不是问题
我的问题/假设是,googleapi库将检查访问令牌是否过期,如果过期,它将自动请求另一个令牌并将其写入'token.json'文件
但从运行这段代码可以看出,在第一次运行时会创建'token.json'文件。即使到期日(1小时)已经过期,谷歌图书馆也不会请求其他代币。我这样说是因为:
.setCredentials()
设置凭据,因此您通过从json文件获取访问令牌来显式声明它
有关代币处理的更多信息,请查看。谢谢@alberto。最后我再次阅读了文档,得出了相同的结论。谢谢你的回答,我会把你的回答记为正确的。