Skip to content

Instantly share code, notes, and snippets.

@ib-lundgren
Created July 8, 2012 11:33
Show Gist options
  • Save ib-lundgren/3070602 to your computer and use it in GitHub Desktop.
Save ib-lundgren/3070602 to your computer and use it in GitHub Desktop.
Explicit no magic OAuth2
# Non magic version, client is only used to append tokens
# All other actions are explicit
import requests
from requests.auth import AuthBase
from oauthlib.oauth2.draft25 import WebApplicationClient
from oauthlib.common import urldecode
class OAuth2WebApp(WebApplicationClient, AuthBase):
def __call__(self, r):
"""Add the OAuth 2 access token to the request."""
r.url, r.headers, r.data = self.add_token(r.url,
http_method=r.method, body=r.data, headers=r.headers)
return r
# Values setup during registration
client_id = u"..."
client_secret = u"..."
authorization_endpoint = u"https://accounts.google.com/o/oauth2/auth"
token_endpoint = u"https://accounts.google.com/o/oauth2/token"
scope = u"https://www.googleapis.com/auth/plus.me"
redirect_uri = u"..."
state = u"ib" # can be anything, used for security reasons
client = OAuth2WebApp(client_id)
auth_uri = client.prepare_request_uri(authorization_endpoint, scope=scope,
redirect_uri=redirect_uri, state=state)
print "Go to this URL and authorize this application"
print auth_uri
response = raw_input("Response URL: ")
params = client.parse_request_uri_response(response, state=state)
# Save params in some db
print "Authorization code", client.code
# Note that the spec does not require neither id nor secret here
# but Google does require it.
data = client.prepare_request_body(code=client.code, redirect_uri=redirect_uri,
client_id=client_id, client_secret=client_secret)
r = requests.post(token_endpoint, data=urldecode(data))
params = client.parse_request_body_response(r.content)
# Save params in some db
print "Access token", client.access_token
print "Token type", client.token_type
# Fetch protected resource using access token
resource_uri = u"https://www.googleapis.com/plus/v1/people/me"
r = requests.get(resource_uri, auth=client)
print r.content
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment