遵循google api文档https://developers.google.com/sheets/api/quickstart/nodejs,找不到通过oauth2客户端使用刷新令牌来获取新令牌的方法。
医生说:"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."
如何通过谷歌oAuth2客户端使用刷新令牌来获取新令牌?
到目前为止,我已经使用了一个简单的帖子
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))
}
但理想情况下,我希望看到更干净的方式。
发布于 2020-11-25 14:04:47
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()
被弃用了(我真想知道为什么)。但由于它仍然有效,这仍然是我要走的路
发布于 2020-10-07 08:33:12
我认为你的代码是正确的,也许你遗漏了一些东西,但我已经在我的NodeJS应用程序中尝试了以下代码,它工作得很好。
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
如果你的所有数据都是正确的,那么上面的代码将返回以下响应:
{
"access_token": "<access-token>",
"expires_in": 3599,
"scope": "https://www.googleapis.com/auth/business.manage",
"token_type": "Bearer"
}
https://stackoverflow.com/questions/61204084
复制