Following google api doc https://developers.google.com/sheets/api/quickstart/nodejs, could not find a way to get a new token using refresh token with the oauth2 client.
The doc says:
"The application should store the refresh token for future use and use the access token to access a Google API. Once the access token expires, the application uses the refresh token to obtain a new one."
How to you get the new token using the refresh token with google oAuth2 Client ?
So far I have managed using a simple post
const getTokenWithRefresh = async (refresh_token) => {
return axios
.post("https://accounts.google.com/o/oauth2/token", {
client_id: clientId,
client_secret: clientSecret,
refresh_token: refresh_token,
grant_type: "refresh_token",
})
.then((response) => {
// TODO save new token here
console.log("response", response.data.access_token);
return response.data;
})
.catch((response) => console.log("error", response))
}
But ideally would like to see cleaner way to do it.
const {google} = require('googleapis')
const getTokenWithRefresh = (secret, refreshToken) => {
let oauth2Client = new google.auth.OAuth2(
secret.clientID,
secret.clientSecret,
secret.redirectUrls
)
oauth2Client.credentials.refresh_token = refreshToken
oauth2Client.refreshAccessToken( (error, tokens) => {
if( !error ){
// persist tokens.access_token
// persist tokens.refresh_token (for future refreshs)
}
})
}
refreshAccessToken()
is deprecated (and I really wonder why). But as it still works, this is still my way to go