pythonoauth-2.0google-fitgoogle-python-api

google-python-api-client refresh token is null


I am trying to use refresh tokens with the google-python-api-client to avoid having to have the user authenticate the app every time.

I have the following code that builds the fitness service by having the user authenticate every time

from apiclient.discovery import build
from oauth2client import tools
from oauth2client.file import Storage
from oauth2client.client import AccessTokenRefreshError
from oauth2client.client import OAuth2WebServerFlow
import httplib2

scope = "https://www.googleapis.com/auth/fitness.activity.read"
flow = OAuth2WebServerFlow(client_id, client_secret, scope, redirect_url)
auth_uri = flow.step1_get_authorize_url()
print auth_uri

token = str(input("Enter token"))

cred = flow.step2_exchange(token)
storage = Storage("credentials_file")
storage.put(cred)

storage = Storage("credentials_file")
cred2 = storage.get()

http = httplib2.Http()
http = cred2.authorize(http)
service = build('fitness', 'v1',http=http)

However, repeatedly authenticating is obviously not ideal so I am trying to convert this into code that can refresh access token using a refresh token. However, after running this code, cred.refresh_token and cred2.refresh_token are both None. How can I obtain the refresh token?


Solution

  • Update, I figured out why it's null

    This line:

    flow = OAuth2WebServerFlow(client_id, client_secret, scope, redirect_url)
    

    Needs to be edited as follows:

    flow = OAuth2WebServerFlow(
                client_id,
                client_secret,
                scope,
                redirect_url,
                approval_prompt='force'
    )