Created
July 8, 2012 11:33
-
-
Save ib-lundgren/3070603 to your computer and use it in GitHub Desktop.
Bit of magic OAuth2
This file contains 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
# 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