Skip to content

Instantly share code, notes, and snippets.

@ib-lundgren
Created July 9, 2012 21:02
Show Gist options
  • Save ib-lundgren/3078882 to your computer and use it in GitHub Desktop.
Save ib-lundgren/3078882 to your computer and use it in GitHub Desktop.
OAuth2 webapp with OAuthLib
# 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
# Very basic auth, only used to append tokens to requests
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
# Confidential client, ie. a webapp connecting to the oauth 2 provider
client = OAuth2WebApp(client_id)
# Similar to the authorization step in OAuth 1 but no request token is
# needed and clients are identified by an explicit 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
# Values are embedded in the query part of the callback
response = raw_input("Response URL: ")
# Params is a dict with response if, commonly used values such as code
# will be set as attributes for convenience
params = client.parse_request_uri_response(response, state=state)
print "Authorization code", client.code
# Normally only the access token is sent here but Google require client id and
# secret as well. Basically embedding http basic auth in the body.
data = client.prepare_request_body(code=client.code, redirect_uri=redirect_uri,
client_id=client_id, client_secret=client_secret)
# Urldecode is needed since data is already urlencoded, dunno if requests has
# a flag to disable urlencoding...
r = requests.post(token_endpoint, data=urldecode(data))
# Once again, a dict of the json response. These are more interesting and have
# values such as token type, access token, expires in, etc.
# For convenience common values are set as attributes
params = client.parse_request_body_response(r.content)
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
# That was OAuth2 with Bearer tokens in a nutshell.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment