I'm using the google-auth-library-nodejs
library to integrate into a number of GMail accounts, to get lists of emails.
My process flow is simple:
1) Try to authorize the client, using this function:
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) The method will check for existence of a token in a file. If the file is NOT found, the following functions will create the file:
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));
}
I am using https://www.googleapis.com/auth/gmail.readonly
as the scopes.
Here's a sample of the file created:
{"access_token":"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx","token_type":"Bearer","refresh_token":"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx","expiry_date":1460509994081}
When processed, here's a sample of the auth object that is returned:
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
}
}
If I delete the file, and go through the manual consent process, then the authentication works 100%, until the token expires. After this, I get the "Invalid Credentials" message.
My assumption is that once the token expires, that the refresh token will be used to auto recreate the access token. Am I missing something?
Here is the updated solution to get Access Token with Refresh Token:
Okay, so I have discovered the
getAccessToken
method, which will check theaccess_token
, and use it, unless it has expired, in which case it will use therefresh_token
to generate a newaccess_token
.