Search code examples
pythongoogle-apigoogle-oauthgmail-apigoogle-api-python-client

RefreshError ('invalid_grant: Token has been expired or revoked.') Google API


About a week ago I set up an application on google. Now when I tri and run:

SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']
creds = None
if os.path.exists('token.pickle'):
     with open(self.CREDENTIALS_PATH+self.conjoiner+'token.pickle', 'rb') as token:
        creds = pickle.load(token)
        if not creds or not creds.valid:
            if creds and creds.expired and creds.refresh_token:
                creds.refresh(Request()) ##error here

I get the following error:

Exception has occurred: RefreshError
('invalid_grant: Token has been expired or revoked.', {'error': 'invalid_grant', 'error_description': 'Token has been expired or revoked.'})

What could be the problem?


Solution

  • token.pickle contains the access token and refresh token for your application.

    Token has been expired or revoked.'

    Means that the refersh token in this file is no longer working this can be caused by servral reasons.

    1. the user revoked your access
    2. The user has authorized your access token more then 50 times and this is the oldest token and was there for expired
    3. the refresh token hasn't been used in six months
    4. The project is still in the testing phase, and there for the refresh token will be expired after seven days.

    All of the above information can be found in Oauth2 expirationdocumentation

    the solution for options 1- 3 is to simply delete the token.pickle file and request authorization of the user again.

    For number four you should go to google developer console under the Oauth2 consent screen and set your application to production. Then your refresh token will stop expiring. Then you can delete the token.pickle and you wont have this issue again.

    enter image description here