Skip to content

Instantly share code, notes, and snippets.

@ib-lundgren
Created July 8, 2012 11:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ib-lundgren/3070603 to your computer and use it in GitHub Desktop.
Save ib-lundgren/3070603 to your computer and use it in GitHub Desktop.
Bit of magic OAuth2
# The slightly magic version, extra requests are made to obtain token
# and users must fetch values from client when saving them to a db
import requests
from requests.auth import AuthBase
from oauthlib.oauth2.draft25 import WebApplicationClient
from oauthlib.common import urldecode, generate_token
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
def authorization_uri(self, uri, scope=None):
self.state = generate_token()
return client.prepare_request_uri(uri, scope=scope, state=self.state)
def fetch_token(self, uri, authorization_response):
client.parse_request_uri_response(response, state=self.state)
data = client.prepare_request_body(code=client.code)
r = requests.post(token_endpoint, data=urldecode(data))
client.parse_request_body_response(r.content)
return client.access_token
# 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"..."
client = OAuth2WebApp(client_id,
default_redirect_uri=redirect_uri,
default_kwargs_body={u"client_id": client_id, u"client_secret": client_secret})
print "Go to this URL and authorize this application"
print client.authorization_uri(authorization_endpoint, scope=scope)
response = raw_input("Response URL: ")
print "Access token", client.fetch_token(token_endpoint, response)
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