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

NodeJS, How to get new token with refresh token using google 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."

如何通过 google oAuth2 客户端使用刷新令牌获取新令牌?

到目前为止,我已经使用简单的 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))
}

但理想情况下希望看到更简洁的方法。

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

如果您的所有数据都正确,以上代码将 return 以下响应:

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

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

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