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

Google Calendar API does not refresh refresh_token


I use the google API for a personal project, so I don't have my app verified with google.

I use exactly this code example myself and a token.json file gets generated when logging in. Everything works fine, the access token changes more or less every time I make a request (every 10 min).

After a week, the request fails. Exactly a week after the "expiry" field in the token.json file.

google.auth.exceptions.RefreshError: ('invalid_grant: Token has been expired or revoked.', {'error': 'invalid_grant', 'error_description': 'Token has been expired or revoked.'})

If I understand everything correctly, google should update refresh_token as well, but this did not happen.

I thought this part would handle getting a new refresh token:

if os.path.exists('token.json'):
    creds = Credentials.from_authorized_user_file('token.json', SCOPES)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
    if creds and creds.expired and creds.refresh_token:
        creds.refresh(Request()) ## HERE ##
    else:

Might this be caused by my app not being verified? I did not find any information and hardly none about the behavior of the refresh_token.


Solution

  • You need to publish your app to production in order to remove the 7 days limitation.

    In APIs & Services / Oauth consent screen:

    enter image description here

    From google documentation about refresh token expiration:

    A Google Cloud Platform project with an OAuth consent screen configured for an external user type and a publishing status of "Testing" is issued a refresh token expiring in 7 days.

    Also about Testing publishing status:

    Projects configured with a publishing status of Testing are limited to up to 100 test users listed in the OAuth consent screen. A test user consumes a project's test user quota once added to the project.

    Google will display a warning message before allowing a specified test user to authorize scopes requested by your project's OAuth clients. The warning message confirms the user has test access to your project but should consider the risks associated with granting access to their data to an unverified app.

    Authorizations by a test user will expire seven days from the time of consent. If your OAuth client requests an offline access type and receives a refresh token, that token will also expire.

    A Brand Account may authorize scopes requested by your project's OAuth clients if a specified test user manages the Brand Account.

    A test user may be unable to authorize scopes requested by your project's OAuth clients due to the availability of Google Services for the account or configured restrictions. A Google Workspace may control which third-party apps access its data or an account enrolled in Advanced Protection may block most non-Google apps.