Created
April 3, 2017 13:50
-
-
Save vijaythakkar/7ca5d55df708f7bb8a1aad184ae76c15 to your computer and use it in GitHub Desktop.
Example python script for REST based OAuth2 for Google Services
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import requests | |
import json | |
import webbrowser | |
import urllib | |
# Goole app setup with "Other" category of credentials, set client id and secret here | |
# Example methods are in order: | |
# get_code() spawn a browser and ask for the user to login | |
# get_token() will take the code from the browser (via manual copy / paste) and generate an auth token | |
# refresh_token() will use the refresh token from get_token() generate a new auth token | |
client_id = "<client_id>" | |
client_secret = "<client_secret>" | |
def get_code(): | |
scopes = ["https://www.googleapis.com/auth/drive", "https://www.googleapis.com/auth/spreadsheets", "https://www.googleapis.com/auth/drive.photos.readonly"] | |
scope_string = " ".join(scopes) | |
url = "https://accounts.google.com/o/oauth2/v2/auth?scope=%s&access_type=offline&include_granted_scopes=true&state=state_parameter_passthrough_value&redirect_uri=urn:ietf:wg:oauth:2.0:oob&response_type=code&client_id=%s&prompt=consent" % (urllib.quote(scope_string, safe=''), client_id) | |
webbrowser.open(url, new=2) | |
def get_token(access_code): | |
headers = {} | |
params = {} | |
params["code"] = access_code | |
params["client_id"] = client_id | |
params["client_secret"] = client_secret | |
params["redirect_uri"] = "urn:ietf:wg:oauth:2.0:oob" | |
params["grant_type"] = "authorization_code" | |
response = requests.post("https://www.googleapis.com/oauth2/v4/token", headers=headers, params=params) | |
return json.loads(response.text) | |
def refresh_token(refresh_token): | |
headers = {} | |
params = {} | |
params["refresh_token"] = refresh_token | |
params["client_id"] = client_id | |
params["client_secret"] = client_secret | |
params["grant_type"] = "refresh_token" | |
response = requests.post("https://www.googleapis.com/oauth2/v4/token", headers=headers, params=params) | |
return json.loads(response.text) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment