我正在使用google-auth-library-nodejs
库集成到多个 GMail 帐户中,以获取电子邮件列表。
我的流程很简单:
1)尝试授权客户端,使用此功能:
function _authorise(mailBox, callback) {
let auth = new googleAuth();
let clientId = eval(`process.env.GMAIL_API_CLIENT_ID_${mailBox.toUpperCase()}`);
let clientSecret = eval(`process.env.GMAIL_API_CLIENT_SECRET_${mailBox.toUpperCase()}`);
let redirectUri = eval(`process.env.GMAIL_API_REDIRECT_URI_${mailBox.toUpperCase()}`);
let tokenFile = process.env.GMAIL_API_TOKEN_PATH + mailBox.toLowerCase()+ process.env.GMAIL_API_TOKEN_BASE_FILE_NAME;
let oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUri);
fs.readFile(tokenFile, ((err, token) => {
if (err) {
_getNewToken(mailBox,oauth2Client,callback);
} else {
oauth2Client.credentials = JSON.parse(token);
callback(oauth2Client);
}
}))
}
2) 该方法将检查文件中是否存在令牌。如果未找到该文件,则以下函数将创建该文件:
function _getNewToken(mailBox, oauth2Client, callback) {
var authUrl = oauth2Client.generateAuthUrl({
access_type: 'offline',
scope: process.env.GMAIL_API_SCOPES
});
console.log('To authorize this app, please use this url: ', authUrl);
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('Enter the code from that page here: ', ((code) => {
rl.close();
oauth2Client.getToken(code, function(err, token) {
if (err) {
console.log('Error while trying to retrieve access token', err);
return;
}
oauth2Client.credentials = token;
_storeToken(mailBox,token);
callback(oauth2Client);
});
}));
}
function _storeToken(mailBox, token) {
let tokenFile = process.env.GMAIL_API_TOKEN_PATH + mailBox.toLowerCase()+ process.env.GMAIL_API_TOKEN_BASE_FILE_NAME;
fs.writeFile(tokenFile, JSON.stringify(token));
}
我在用https://www.googleapis.com/auth/gmail.readonly
用作范围。
这是创建的文件的示例:
{"access_token":"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx","token_type":"Bearer","refresh_token":"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx","expiry_date":1460509994081}
处理后,这是返回的 auth 对象的示例:
OAuth2Client {
transporter: DefaultTransporter {},
clientId_: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com',
clientSecret_: 'xxxxxxxxxxxxxxxxxxxxxxxx',
redirectUri_: 'urn:ietf:wg:oauth:2.0:oob',
opts: {},
credentials: {
access_token: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
token_type: 'Bearer',
refresh_token: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
expiry_date: 1460509994081
}
}
如果我删除该文件,并通过手动同意过程,那么身份验证工作 100%,直到令牌过期。在此之后,我收到“无效凭据”消息。
我的假设是,一旦令牌过期,刷新令牌将用于自动重新创建访问令牌。我错过了什么吗?