Passport JS / Google Login

Passport Google Login and the Refresh Token

Tutorials can be such a pain. On the one hand, they can be great for getting started with a new technology, but quickly you realize that you need to do more than the tutorial shows. That’s when the Googling starts!

I encountered this when building whendidiwork, an Express app using Passport and the Google Oauth strategy. I could successfully login and receive the access and refresh tokens, but how to monitor the expiration time of the token and make the exchange when the time comes?

In this app I used passport to handle authentication, and for my api calls I utilize the googleapis library. This library has a method for manually refreshing a token. So I set up route middleware that checks the expiry time against the current time, and if there is less than 5 minutes left, the token is refreshed and then saved to the database.

So how did I get the expiry time of the access token? It turns out that if you pass the params parameter to the passport strategy callback, you will receive an object that looks like this.

  params = {
    access_token: 'Long_string',
    token_type: 'Bearer',
    expires_in: 3599, // seconds
    id_token: 'Longer_string'

From this you can calculate the expiry time and save it to the database.

Here is the code for the route middleware. Remember to always call next() when it is time to go on to the next step.

The last step is to tell the router to use the middleware that we just created.

Now the token will be checked for expiration on every route on which the middleware is used.

The full source code from which I pulled this example can be found here in the whendidiwork-react repo. If you have any questions, or have found a better way of going about this, feel free to let me know.

Brandon Lehr

I'm Brandon Lehr, a web developer, machinist, and sometimes mechanic (when the truck breaks down). I guess you could say that I enjoy solving problems and building things.

The Pack Admin - Free Software for managing Cub Scout Packs