Access Token and Refresh token giving invalid grant in Google Plus in Python?

前端 未结 5 853
野的像风
野的像风 2020-12-18 04:35

I am correctly scoping for offline access and am storing that. Every 60 minutes, when needed, I retrieve a new access_token. Code has not changed, but what is odd is that wh

5条回答
  •  北海茫月
    2020-12-18 05:11

    You might want to try adopting the approach used in the Google+ Python Hybrid auth sample and let the library manage the OAuth 2 tokens. A full example is here:

    https://developers.google.com/+/quickstart/python

    In that sample, code exchange is performed using Google's library and the credentials are stored in a basic session on success (you should use a DB in practice):

    # Retrieve authorization code from POST data
    code = request.data
    
    try:
      # Upgrade the authorization code into a credentials object
      oauth_flow = flow_from_clientsecrets('client_secrets.json', scope='')
      oauth_flow.redirect_uri = 'postmessage'
      credentials = oauth_flow.step2_exchange(code)
    except FlowExchangeError:
      response = make_response(
        json.dumps('Failed to upgrade the authorization code.'), 401)
      response.headers['Content-Type'] = 'application/json'
      return response
    
    #... other code ...
    session['credentials'] = credentials
    

    Later on, you can just retrieve the credentials (from the session or db) and the Python library does the rest.

    """Get list of people user has shared with this app."""
    credentials = session.get('credentials')
    # Only fetch a list of people for connected users.
    if credentials is None:
      response = make_response(json.dumps('Current user not connected.'), 401)
      response.headers['Content-Type'] = 'application/json'
      return response
    try:
      # Create a new authorized API client.
      http = httplib2.Http()
      http = credentials.authorize(http)
      # Get a list of people that this user has shared with this app.
      google_request = SERVICE.people().list(userId='me', collection='visible')
      result = google_request.execute(http=http)
    
      response = make_response(json.dumps(result), 200)
      response.headers['Content-Type'] = 'application/json'
      return response
    except AccessTokenRefreshError:
      response = make_response(json.dumps('Failed to refresh access token.'), 500)
      response.headers['Content-Type'] = 'application/json'
      return response
    

提交回复
热议问题