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.
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"
}
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.