-
Notifications
You must be signed in to change notification settings - Fork 2
How to get OAuth access token in console?
To access Google Spreadsheets API using OAuth2 authentication, you provide an access token instead of UID/PWD. A third-party can allow Google to give you the token, so you can act on their behalf. The token gives you permissions only within a very restricted subset of the user's services. You have no possibility of taking over their account.
The procedure below documents complete, step-by-step instructions for obtaining, using and refreshing an OAuth access token for GSpread.
It is a bare bones method. If you need production quality, you will have to learn one of the many python librarires for OAuth :
I've brought together python code snippets scattered across official documentation like the Google OAuth python guide into a simple script I'd like to share. It is published as GitHub gist burnash/6771295. A contributor has provided an alternate version that is compatible with token refreshing, and avoids a function that Google deprecated recently.
Below are the preparatory steps you need to follow before you can use either of those scripts. Also, note that Google recently did a complete overhaul of their API Console. The steps below show you how to get your OAuth credentials with both methods.
At the first page "dashboard", click on the project drop down, to create a new project.
Select "create" from the drop down.
Enter your choice of project name . . .
. . . and click [Create project]
On the project page click on the [API Access] menu option and then the big blue button.
Provide your preferred details for "Product name", "Product logo" and "Home Page URL" . . .
. . . then click [Next]
Select the radio buttons for "Installed application" and "Other" and click [Create client ID]
You can now copy the "Client ID" and "Client secret" for use in GSpread.
At the first page "dashboard", click on [CREATE PROJECT].
Provide a Product name and some sort of unique Project ID.
Open the menu [APIs & Auth] . . .
. . . and its submenu [Registered apps].
Click on [REGISTER APP]
Provide an application Name and choose the [Native] radio button for Platform type. Then click the [Register] button.
Get ready to copy'n paste the CLIENT ID and CLIENT SECRET into a GSpread test script (below).
-
Get my Python script from gist: https://gist.github.com/burnash/6771295 and save it as
get_oauth2_token.pysomewhere on your local path. -
Open it with your editor.
-
Replace
CLIENT_IDandCLIENT_SECRETwith your data from Google API Console (see red arrows on the screenshot). -
Install dependencies:
$ pip install python-gflags oauth2client- Run the script:
$ python get_oauth2_token.py- Your default browser will open up a page with authentication prompt.
Upon your successful sign up the page will redirect you to http://localhost:8080 with a text "The authentication flow has completed."
- You get your access token as an output in a console:
Your browser has been opened to visit:
https://accounts.google.com/o/oauth2/auth?scope=https%3A%2F%2Fspreadsheets.google.com%2Ffeeds+https%3A%2F%2Fdocs.google.com%2Ffeeds&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2F&response_type=code&client_id=1.apps.googleusercontent.com&access_type=offline
If your browser is on a different machine then exit and re-run this application with the command-line parameter
--noauth_local_webserver
Authentication successful.
access_token: ma29.AHES6ZTtHMjvGinGzdXXte4XPGSRsVuLpNPTzWB_lZpY7MJjHehAyA
To ensure safe testing, these instructions include using virtualenv. They describe how to prepare a temporary, disposable virtual environment that will not affect your permanent Python configuration.
- Use pip to install virtualenv, create a directory to work in and then activate it for immediate use in isolation from the rest of the machine.
sudo pip install virtualenv
mkdir safe_test_dir
virtualenv safe_test_dir
cd safe_test_dir
source ./bin/activate
- Install required dependency, Google's OAuth tool kit:
pip install oauth2client- Download gspread, decompress it and install it.
wget -O gspread.zip https://codeload.github.com/FleetingClouds/gspread/zip/master
unzip gspread.zip
rm -f gspread.zip
mv gspread-master gspread
cd gspread
python ./setup.py install
cd ..- Get the contributed Python script package from gist: https://gist.github.com/martinhbramwell/7553524 decompress it, and move the contained script into the current directory.
wget -O gistFile.tar.gz https://gist.github.com/martinhbramwell/7553524/download
tar -zvxf gistFile.tar.gz
mv gist*/get_google_oauth2_creds.py .
rm -fr gist*- Run the script, (get_google_oauth2_creds.py)
python get_google_oauth2_creds.py- You will see the following. Provide the requested Client ID, Client secret and spreadsheet URL when prompted.
You will be asked for a Google "Client ID", a "Client Secret" and the URL of the spreadsheet you want to access.
To get the ID and Secret, follow the procedure here :
https://github.com/FleetingClouds/gspread/wiki/How-to-get-OAuth-access-token-in-console%3F.
Paste your Google "Client ID" : 53120518******************rq2nbfro.apps.googleusercontent.com
Paste your Google "Client Secret" : oGnuOp*************Z1vS5R
Paste the full URL, including the "http://" etc, etc, of the Google spreadsheet you want to use : https://docs.google.com/spreadsheet/ccc?key=0AhgdN**************************tY2NVYTNOaVE&usp=drive_web#gid=76- The script passes control to Google's Python library oauth2client, which displays the following help text, and then waits for confirmation/rejection from Google. (If you need it you can edit the code to change noauth_local_webserver from False to True.)
Your browser has been opened to visit:
https://accounts.google.com/o/oauth2/auth?scope=https%3A%2F%2Fspreadsheets.google.com%2Ffeeds+https%3A%2F%2Fdocs.google.com%2Ffeeds&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2F&response_type=code&client_id=531205187158-2eel3k40kqpt9jaoj2aeq2torq2nbfro.apps.googleusercontent.com&access_type=offline
If your browser is on a different machine then exit and re-run this application with the command-line parameter
--noauth_local_webserver- Your default browser will open a page on Google's servers with the OAuth authentication dialog.
If you accept, the page will redirect you to http://localhost:8080 with the response text "The authentication flow has completed."
- Back at your command line console window the final result will appear.
Authentication successful.
Create an empty text file called qiktest.py
Paste the following lines into it.
Execute with:
$ python qiktest.py
# - - - - - - - - - - - - - - - - - - - - - - - - - - -
# -*- coding: utf-8 -*-
import gspread
#
refresh_token = '1/8FWpr4z*******************us8OCQE-ccA'
client_secret = 'oGnuO**************1vS5R'
client_id = '53120518*****************bfro.apps.googleusercontent.com'
#
key_ring = {}
key_ring['grant_type'] = 'refresh_token'
key_ring['refresh_token'] = refresh_token
key_ring['client_secret'] = client_secret
key_ring['client_id'] = client_id
#
access_token = 'ya29.1.AADtN_Vf6******************************************36DpBVqA'
gc = gspread.authorize(access_token, key_ring)
#
wkbk = gc.open_by_url('https://docs.google.com/spreadsheet/ccc?key=0AhgdNB3-*******************VYTNOaVE&usp=drive_web#gid=76')
cnt = 1
print 'Found sheets:'
for sheet in wkbk.worksheets():
print ' - Sheet #{}: Id = {} Title = {}'.format(cnt, sheet.id, sheet.title)
cnt += 1
#
# - - - - - - - - - - - - - - - - - - - - - - - - - - -- All of the output text, between the dashed comment lines, comprise a working Python program. Create an empty text file, called something like qiktest.py, paste the program code lines into it, and then execute with:
python qiktest.py















