user1253952
user1253952

Reputation: 1597

invalid_grant Error when Authenticating oauth Request - Google Drive

I am attempting to get access to a customer's Google Drive to download their files. When testing the code on my own google drive, I am able to successfully download files. However, when I get the oauth code from them, I get the error:

oauth2client.client.FlowExchangeError: invalid_grant

After looking at some of the other answers, it has been suggested that you ensure access_type='offline', which seems to be the default and I can see in the generated url that this parameter is set. It also sounds like the code they give back may only be valid for an hour, however I have tried to use it within the hour and still no luck. Any other suggestions for how to avoid this problem?

Here is the code I have been running:

from oauth2client import client
import webbrowser

flow = client.flow_from_clientsecrets(
  'client_secrets.json',
  scope='https://www.googleapis.com/auth/drive.readonly',
  redirect_uri='urn:ietf:wg:oauth:2.0:oob')

auth_uri = flow.step1_get_authorize_url()
webbrowser.open(auth_uri)

print auth_uri

auth_code = raw_input('Enter the auth code: ')

credentials = flow.step2_exchange(auth_code)
http_auth = credentials.authorize(httplib2.Http())

It errors on the flow.step2_exchange line.

Upvotes: 0

Views: 1592

Answers (1)

Linda Lawton - DaImTo
Linda Lawton - DaImTo

Reputation: 116868

There are three standard causes for this error that I am aware of.

  1. The time is off on your PC. Solution: check it.
  2. You are trying to use an authentication code more then once. You can only use the authentication code once to get the refresh token.
  3. You are testing and authenticating the code more then once. Each time you authenticate the code you get a valid refresh token. You can get up to 25 refresh tokens and then they stop working. Solution: make sure that every time you refresh the access you are using that refresh token and not an older one.

Also google as a Python tutorial that shows you how to access drive using the Python Client library it may make things easer for you. Python QuickStart

Upvotes: 1

Related Questions