Why am I getting invalid_grant for Google API call

2019-07-15 03:20发布

I'm trying to access Google Prediction API from App Engine and following instructions here -- https://developers.google.com/appengine/articles/prediction_service_accounts

This works great when deployed on App Engine. The same code, however, fails with the following error on the local devserver.

credentials = AppAssertionCredentials(
              scope='https://www.googleapis.com/auth/prediction')
http = credentials.authorize(httplib2.Http(memcache))
service = build("prediction", "v1.5", http=http, developerKey=api_key)

ERROR    2012-12-28 03:48:53,084 client.py:461] Failed to retrieve access token: {
  "error" : "invalid_grant"
}
ERROR    2012-12-28 03:48:53,115 cgi.py:121] Traceback (most recent call last):
  File "/Users/gkedia/git/thirdgaze/main.py", line 83, in <module>
    service = build('prediction', 'v1.5', http=http, developerKey=api_key)
  File "/Users/gkedia/git/thirdgaze/apiclient/discovery.py", line 175, in build
    resp, content = http.request(requested_url)
  File "/Users/gkedia/git/thirdgaze/oauth2client/client.py", line 503, in new_request
    self._refresh(request_orig)
  File "/Users/gkedia/git/thirdgaze/oauth2client/client.py", line 412, in _refresh
    self._do_refresh_request(http_request)
  File "/Users/gkedia/git/thirdgaze/oauth2client/client.py", line 472, in _do_refresh_request
    raise AccessTokenRefreshError(error_msg)
AccessTokenRefreshError: invalid_grant

One of the things I noticed was for the exact same parameters, key_name, signature = app_identity.sign_blob(base_str) returns different signature in production and on local machine.

My computer's time is sync'ed correctly and offline_access parameter doesn't seem to be involved yet.

1条回答
SAY GOODBYE
2楼-- · 2019-07-15 03:29

app_identity and more generally service account won't work on dev_appserver you would have to fallback a regular oauth2 webserver flow in order to get an access token associated with a regular Google Account when testing locally.

Something like:

flow = OAuth2WebServerFlow(client_id='your_client_id',
                           client_secret='your_client_secret',
                           scope='https://www.googleapis.com/auth/prediction',
                           redirect_uri='http://localhost:8080/oauth2callback')
self.redirect(flow.step1_get_authorize_url())

And then in /oauth2callback handler:

credentials = flow.step2_exchange(self.request.get('code'))
http = credentials.authorize(httplib2.Http(memcache))
service = build("prediction", "v1.5", http=http, developerKey=api_key)

You can easily detect if you are running on the dev_appserver or in production using SERVER_SOFTWARE environment variable.

查看更多
登录 后发表回答