NodeJS,如何使用谷歌api获得带有刷新令牌的新令牌



跟随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))
}

但理想情况下,希望看到更清洁的方式来做到这一点。

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()已被弃用(我真的很想知道为什么(。但由于它仍然有效,这仍然是我的之路

我认为你的代码是正确的,也许你错过了一些东西,但我已经在我的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"
}

const getAccessToken = async () => {
try {
let tokenDetails = await axios.post("https://accounts.google.com/o/oauth2/token", {
"client_id": {your-clientId},
"client_secret": {your-secret},
"refresh_token": {your-refreshToken}
grant_type: "refresh_token",
})
const accessToken = tokenDetails.data.access_token
return accessToken
} catch (error) {
return error
}
}
getAccessToken()
.then(data=> console.log(data))
.catch(err => console.log(err))

我想这可能对你有帮助
编码快乐!

最新更新