Google-api-nodejs-client: Refresh access_token manually

Created on 10 Dec 2019  路  3Comments  路  Source: googleapis/google-api-nodejs-client

I checked doc and most of the issues about tokens workflow but it does not make sense for me
in some cases we need to refresh access_token manually.

a brief resume about our system
we handle auth and store tokens in backend
and we send access_token to front end to request
once the access_token expired frontend will send to backend to refresh it and receive the new one .

      const oauth2Client = new google.auth.OAuth2(
            process.env.GOOGLE_CLIENT_ID,
            process.env.GOOGLE_SECRET_ID,
            process.env.GOOGLE_REDIRECT_URI
        );

        let account =  await model.Account.findByPk(args.account_id)
        if(!account) return 'ACCOUNT_NOT_FOUND'

        if(!account.auth_data.google_access_tokens.refresh_token){
            return 'REFRESH_TOKEN_IS_MISSING'
        }
        oauth2Client.setCredentials({
            refresh_token: account.auth_data.google_access_tokens.refresh_token,
            access_token : account.auth_data.google_access_tokens.access_token
          });

          oauth2Client.on('tokens', async (tokens) => {

            console.log(tokens)  <---------------------- normally when the access_token got expired it will trigger this event and log and object contains token no ?

          });      

Thank you in advance

question

Most helpful comment

I Solved by using api directly

const response = await axios.post('https://oauth2.googleapis.com/token',
                            {client_id : process.env.GOOGLE_CLIENT_ID,
                             client_secret : process.env.GOOGLE_SECRET_ID,
                             grant_type    : 'refresh_token',
                             refresh_token :db.refresh_token})

All 3 comments

I Solved by using api directly

const response = await axios.post('https://oauth2.googleapis.com/token',
                            {client_id : process.env.GOOGLE_CLIENT_ID,
                             client_secret : process.env.GOOGLE_SECRET_ID,
                             grant_type    : 'refresh_token',
                             refresh_token :db.refresh_token})

I think smth similar needs to be added in the official nodejs library to easier manage this.

@botzill I would look at https://github.com/googleapis/google-auth-library-nodejs, rather than this repo; It provides a lower level interface to Google's OAuth APIs.

It allows you to create a UserRefreshClient, which will handle your refresh token for you.

Was this page helpful?
0 / 5 - 0 ratings