google-auth-library-nodejs icon indicating copy to clipboard operation
google-auth-library-nodejs copied to clipboard

Refresh the token in an AWS Lambda function

Open baptisteArno opened this issue 2 years ago • 1 comments

The library works perfectly on my machine but when it's deployed in a Lambda function, the token doesn't seem to automatically update:

export const getAuthenticatedGoogleClient = async (
  userId: string,
  credentialsId: string
): Promise<OAuth2Client | undefined> => {
  const credentials = (await prisma.credentials.findFirst({
    where: { id: credentialsId, ownerId: userId },
  })) as CredentialsFromDb | undefined
  oauth2Client.setCredentials(credentials)
  oauth2Client.on('tokens', updateTokens(credentialsId))
  return oauth2Client
}

const updateTokens = (credentialsId: string) => async (credentials) =>
   prisma.credentials.update({
      where: { id: credentialsId },
      data: { credentials },
    })

My guess is that it doesn't have time to update in the database because this is handled in a callback.

Is there a way to check if expiry_date is passed and update the token with a Promise-based function?

Some examples of errors I get: CleanShot 2022-03-04 at 21 07 02@2x

baptisteArno avatar Mar 04 '22 20:03 baptisteArno

Oooooh I think I know, I think the tokens from the callback don't contain the refresh_token so I pushed credentials in db without the refresh_token!

baptisteArno avatar Mar 04 '22 20:03 baptisteArno

Hey, apologies for the delay - I would recommend storing the refresh_token when it is available in the callback (usually, the initial authorization):

  • https://github.com/googleapis/google-api-nodejs-client/issues/750#issuecomment-304521450

Here's some documentation as well: https://github.com/googleapis/google-auth-library-nodejs#handling-token-events

danielbankhead avatar Sep 29 '23 22:09 danielbankhead