'Token has been expired or revoked' - Google OAuth2 Refresh token gets expired in a few days

Viewed 21324

I am using Google Analytics API to fetch analytics data. I tried to authenticate it using following steps:

  • Created OAuth client ID in https://console.developers.google.com/ credentials section.
  • In consent screen I had set publishing status as testing
  • In OAuth 2.0 Playground I got the refresh token using above generated client id and client secret
  • Then I am using it to generate access token through it.

But after a few days, the refresh token expires although it is mentioned that the refresh token's validity is life long.

6 Answers

I needed to send mails from a gmail account that I have access to, using nodemailer. It works for a couple of days before my refresh token is mysteriously revoked, even though the account belongs to me. A google search brought me here and I had been watching for a while hoping someone would help with a solution.

As you mentioned, this seems to happen with only test/unverified apps and I'm guessing google revokes tokens for such applications in your account after a few days. After much trials and errors, here is what I did.

NOTE: This is solution is only applicable to accounts you own, otherwise you must verify your app to access other people's accounts

  1. Generate a new refresh token (existing one is most likely revoked) as described in this SO post
  2. Go to the security tab of your google account dashboard
  3. Under the Recent security activity section, you should see a security alert for your app.
  4. Click on the context menu next to the notification and click DISMISS
  5. At this point you'll be presented with a dialog of options where you indicate the level of trust you have for the app. I just went ahead and said I trusted the developer/app, obviously. And that's it! The refresh token should persist after this.

I could not find anything related anywhere else.

The other answer pointed me in the right direction but for me the option was located somewhere else: security > security checkup/security issues found > context menu next to your app > dismiss

This issue seems to be for unverified apps, Simply delete the token file from your project and rerun the project, it will create a new token.

My problem was when I've added access_token instead of refresh_token.

The solution is to delete your token.json file to force Google to find a new token.

I was able to get it to work WITHOUT a verified app. Perhaps the refresh() method will work once my app is verified. Not sure on that one.

Related