Search code examples
gmailgoogle-oauthcypressaccess-token

How to refresh tokens for gmail api programmatically?


I'm writing Cypress tests that need to run in CI and some of those tests require checking gmail. I followed the gmail api quickstart and used the provided program to generate a token that's saved to disk. The token is saved with this format:

{
   access_token:
   refresh_token:
   scope:
   token_type:
   expiry_date:

 } 

The token contains a refresh token so I can reuse the same file for my tests and it works. But after about 7/8 days the tests fail, saying the token's been revoked.

I want to make another request for a new token, but the program provided in the quickstart needs to be done manually (provides a link that a person visits, signs in with their gmail, get a code they paste back in the terminal). Is there any way to request a new token programatically?


Solution

  • If your refresh token has expired then the only way to get a new one is to request access of the user whos data you are trying to access by displaying the consent screen to them.

    I think the main issue is why your refresh token is expiring for the most part refresh tokens shouldnt expire however ..

    Refresh tokens for apps which are in production and have been through googles verification process do not expire

    refresh tokens which were created by applications which are still in testing only last at max two weeks.

    If the user changes their password this can also expire a refresh token which was created using gmail scopes