Search code examples
pythongoogle-oauthaccess-token

How can I refresh a stored Google oAuth credential


I'm using the Python API that google provides. What I want to do is just make sure that the access token doesn't expire. I have the refresh_token stored in the credentials file. I'm just not sure how to 'check' that the token is still good before making the call to the API and if need be refreshing it and re-storing it in the credentials file.

I did a test that even if I delete the access tokens from the credentials file that it rewrites them into it using the refresh token. I'm hoping that will work for expired access tokens as well.

Thanks

storage = Storage('cred_storage.txt')

credentials = storage.get()

if not credentials:
    flow = OAuth2WebServerFlow(CLIENT_ID, CLIENT_SECRET, OAUTH_SCOPE, REDIRECT_URI)
    authorize_url = flow.step1_get_authorize_url()
    print 'Go to the following link in your browser: ' + authorize_url
    code = raw_input('Enter verification code: ').strip()
    credentials = flow.step2_exchange(code)
    storage.put(credentials)


http = httplib2.Http()
http = credentials.authorize(http)
print http
service = build('admin', 'reports_v1', http=http)
print service
data_query = service.customerUsageReports().get(**{'date':'2015-01-07'})
feed = data_query.execute()
print feed

Solution

  • Simply check the case of expired access token and refresh your expired access token like this:

    if credentials.access_token_expired:
        credentials.refresh(httplib2.Http())
    

    Tip: While developing this, you can test by editing the access token expiry date in the credentials text file and forcing it to be older than an hour

    Also, in your code on the line where you are checking if not credentials:, you can better handle that case with:

    if credentials is None or credentials.invalid: