【问题标题】:NodeJS, How to get new token with refresh token using google api?NodeJS,如何使用谷歌 api 获取带有刷新令牌的新令牌?
【发布时间】:2020-07-26 23:13:56
【问题描述】:

按照 google api doc 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."

如何通过 google oAuth2 Client 使用刷新令牌获取新令牌?

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

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

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

【问题讨论】:

  • 刷新令牌只要被使用就不会过期,为什么要获得一个新令牌?

标签: node.js google-sheets google-api google-oauth google-api-nodejs-client


【解决方案1】:
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() 已被弃用(我真的很想知道为什么)。但由于它仍然有效,这仍然是我要走的路

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 我收到了id_token 对您上面提到的这些属性的回复,这个回复中的id_token 是什么?
    • 你好@KamalHossain,你使用的是同一个API吗?
    • 我不再需要这个解决方案,我终于用了这个react google login。 @Keyur Chavda-kc1994
    猜你喜欢
    • 2013-07-20
    • 1970-01-01
    • 2021-01-29
    • 1970-01-01
    • 2014-01-11
    • 2021-05-06
    • 2017-04-19
    • 2018-10-14
    • 2014-03-31
    相关资源
    最近更新 更多