Georges Pompidou Georges Pompidou - 1 year ago 138
Node.js Question

Google API invalid request after access token expires

This is the comment that led me to ask this question.

I've got a server side Node.js app, using googleapis package. Users log in with their Google accounts, and I store tokens in their session. The credentials I get are as follows

{ access_token: '<AN ACCESS TOKEN>',
token_type: 'Bearer',
id_token: '<A LONG ID TOKEN>',
expiry_date: <A TIMESTAMP> } // why do some places say there's an expires_in instead of this

There's no
because the users have already logged in for the first time and clicked accept, and I didn't store the refresh token (looks like I should've).

So, when the
is reached, if the user tries to make a request for us to save something to their google drive, I get an error message:

{ [Error: invalid_request] code: 400 } // further details

My 2-part question:

  • I assume I'm getting that error message because the access_token in my OAuth client object is expired (because the call works fine before the token expires). Is this correct? Why is the error message not more detailed?

  • In the linked answer at the top, the solution is to force the accept prompt again, get the refresh token, and store it permanently, and use it to get a new access token when it expires. Why is this a better option than just checking if the token is expired, and having a user reauthenticate when we want to make a call to the API? Which is the "correct" way to ensure that my logged in users can always make the drive API call to save their documents?

Answer Source
  1. Right, the 400 response is because of the expired access token. I'm not sure why Google doesn't give more detail, but it's common for services to use the 400 status code to indicate some kind of credentials problem. The definition of the status code indicates that it's a client issue.

  2. Both approaches will work and they each have advantages and disadvantages. The client-side re-authentication method you're suggesting has the advantage of making the implementation simpler, since you don't have to store the refresh token and don't have to implement the refresh process. The downside is that forcing the user to re-authenticate every hour is less user-friendly. At the least they will be redirected away from your app, and they may have to explicitly log in or re-authorize as well. You'll just have to look at the trade-offs and pick what works best for your use case.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download