Zephyr
Zephyr

Reputation: 2322

Gmail API's access token expiration and creation

I've been using google API to send emails from the server in my node.js project. I've setup credentials and created a refresh token and access token and have been using the same for over 6 months like so.

oAuth2Client = new google.auth.OAuth2(client_id, client_secret, redirect_uris);
oAuth2Client.setCredentials({ refresh_token, access_token, scope, expiry_date });
gmail = google.gmail({ version: 'v1', oAuth2Client });
gmail.users.messages.send({ /* email details */ });

The expiry_date I'm sending is the one I received when I created my tokens the first time and so the date is a past date (over 6 months).

I remember reading that the access token expires after sometime but I'm not sure when my access_token will expire or how I'd go about creating a new one. My emails are still being sent so I'm a little confused as to why it hasn't stopped working yet.

So my questions are essentially

  1. How do I find out when my access_token will expire.
  2. Once it does expire how do I create a new one. While setting all this up the first time I remember doing it in playground but I'd prefer to set up the access_token creation process in the server code itself if I can.

Upvotes: 4

Views: 6890

Answers (1)

Linda Lawton - DaImTo
Linda Lawton - DaImTo

Reputation: 116868

Access tokens expire after one hour. The best and only way to know if it has expired is to try it if the access token has expired the API will return an error to you.

Refresh tokens on the other hand for the most part will not expire. Your code is most likely using the refresh token properly to request a new access token when ever it needs one. This functionality is built into the Google apis js client library for you and is not something you need to consider.

how a refresh token can expire

  1. the user can remove your access via their Google account.
  2. If the access token has not been used in six months google will automatically expire it.
  3. If you request authorization (Show the consent screen) to the user you will get a refresh token back. If you do it again you will get another refresh token¸ both will work. You can have up to fifty outstanding refresh tokens for a given user once you have hit that mark the first one will expire.
  4. Weird bug from a few years ago that when daylight savings time hit a lot of Google refresh tokens were automatically expired due to some weird bug on their end which has not happens again since :)

Upvotes: 6

Related Questions