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.
Click on Authorize APIs button and select your Gmail account when you are asked and allow the scopes. Under Step 2, click Exchange authorization code for tokens to generate and display the Access Token and Refresh Token.
In order to get an access token with a refresh token, you just need to ask for the offline access type (for example in PHP: $client->setAccessType("offline"); ) and you will get 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
Your code is I think correct maybe you missed something but I've tried the following code in my NodeJS application, and its working well.
let tokenDetails = await fetch("https://accounts.google.com/o/oauth2/token", {
"method": "POST",
"body": JSON.stringify({
"client_id": {your-clientId},
"client_secret": {your-secret},
"refresh_token": {your-refreshToken},
"grant_type": "refresh_token",
})
});
tokenDetails = await tokenDetails.json();
console.log("tokenDetails");
console.log(JSON.stringify(tokenDetails,null,2)); // => Complete Response
const accessToken = tokenDetails.access_token; // => Store access token
Above code will return following response if your all data are correct then:
{
"access_token": "<access-token>",
"expires_in": 3599,
"scope": "https://www.googleapis.com/auth/business.manage",
"token_type": "Bearer"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With