Reputation: 1452
My Python code need access the files in GCS, I'm stuck at the authentication.
I read https://developers.google.com/api-client-library/python/guide/aaa_oauth and add below code for auth:
flow = OAuth2WebServerFlow( client_id='995.apps.googleusercontent.com',
client_secret='Zcxxxxxxxx',
scope='https://www.googleapis.com/auth/devstorage.read_only',
redirect_uri='urn:ietf:wg:oauth:2.0:oob')
auth_uri = flow.step1_get_authorize_url()
credentials = flow.step2_exchange('3/xxxxxxxxxxxxx') # I copy the code returned in
# browser after opening the
# URL of auth_uri
http = httplib2.Http()
http = credentials.authorize(http)
client = discovery.build('storage', 'v1beta2', http=http)
request = client.objects().list(
bucket = 'mybucket',
prefix = 'myfolder/sub-folder',
key = 'xxxxxx_2Ks') # my API key
I know the code should be incorrect, because it is not possible to open a browser to get the code and enter back manually in the Python program.
I hope my code can just get the client id, client secret, scope and redirect, then can create authorized request which can be used for long time, is it possible?
Could someone advise and provide simple sample code? Thanks for all kind help!
===================================
Update at 03/21:
I also tried below code just now and wanted to get my code Pass at least one time..
auth_uri = flow.step1_get_authorize_url()
webbrowser.open(auth_uri)
mycode = input("Please input the code: ")
credentials = flow.step2_exchange(mycode)
http = httplib2.Http()
http = credentials.authorize(http)
client = discovery.build('storage', 'v1beta2', http=http)
request = client.objects().list(.....)
When I tried to use the request, but got oauth2client.client.FlowExchangeError: invalid_request.
Upvotes: 0
Views: 324
Reputation: 5509
If you run the code you posted and copy/paste a single time from the browser, then you should have a valid credentials object. To avoid needing to use the browser in future runs, you can save off the refresh token like so:
# Save refresh token (to file or elsewhere)
with open('refresh_token_file', 'w') as token_file:
token_file.write(credentials.refresh_token)
Then, later on, you can load that refresh token that you saved (without any interaction with a browser) and associate that token with a new httplib2.Http:
# Load refresh token from file (or wherever it's stored) into saved_refresh_token)
# ...
credentials = OAuth2Credentials(None, your_client_id, your_client_secret, saved_refresh_token, None, 'https://accounts.google.com/o/oauth2/token', None)
credentials.refresh(http)
Make sure that wherever you choose to save the token is secure. It should be accessible only to you and people with have the authority to act as you.
Upvotes: 1