首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >NodeJS,如何使用google api获取带有刷新令牌的新令牌?

NodeJS,如何使用google api获取带有刷新令牌的新令牌?
EN

Stack Overflow用户
提问于 2020-04-14 09:01:40
回答 2查看 5.2K关注 0票数 5

遵循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客户端使用刷新令牌来获取新令牌?

到目前为止,我已经使用了一个简单的帖子

代码语言:javascript
运行
AI代码解释
复制
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))
}

但理想情况下,我希望看到更干净的方式。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-11-25 14:04:47

代码语言:javascript
运行
AI代码解释
复制
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()被弃用了(我真想知道为什么)。但由于它仍然有效,这仍然是我要走的路

票数 5
EN

Stack Overflow用户

发布于 2020-10-07 08:33:12

我认为你的代码是正确的,也许你遗漏了一些东西,但我已经在我的NodeJS应用程序中尝试了以下代码,它工作得很好。

代码语言:javascript
运行
AI代码解释
复制
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

如果你的所有数据都是正确的,那么上面的代码将返回以下响应:

代码语言:javascript
运行
AI代码解释
复制
{
  "access_token": "<access-token>",
  "expires_in": 3599,
  "scope": "https://www.googleapis.com/auth/business.manage",
  "token_type": "Bearer"
}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61204084

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档