Skip to content

Instantly share code, notes, and snippets.

@st4lk
Last active August 29, 2015 14:21
Show Gist options
  • Save st4lk/af1db97e36897b918f22 to your computer and use it in GitHub Desktop.
Save st4lk/af1db97e36897b918f22 to your computer and use it in GitHub Desktop.
"""
Example of OAuth 2.0 process with client-side only web page.
We can access to user's resources without providing a client_secret!
Given access_token will be short-lived, about 1 or 2 hours, whereas
access_token given by server-side workflow is long-lived, up to 60 days.
http://stackoverflow.com/questions/9067947/facebook-access-token-server-side-vs-client-side-flows
API of facebook is used: https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow
"""
import webbrowser
import urllib2
import json
from urllib import urlencode
from urlparse import parse_qsl, urlparse
import random
CLIENT_KEY = 'your_app_key'
CLIENT_SECRET = None # Not needed here!
AUTHORIZE_URL = 'https://www.facebook.com/dialog/oauth'
ACCESS_TOKEN_URL = 'https://graph.facebook.com/v2.3/oauth/access_token'
API_RESOURCE_URL = 'https://graph.facebook.com/v2.3/me'
# host must be set explicitly in facebook app configuration, otherwise forbidden
CALLBACK_URL = "http://rrhosterer.com:8000/oauth2"
###########################################
# STEP 1: user cofirmation and access_token
###########################################
auth_params = {
"client_id": CLIENT_KEY,
"state": str(random.getrandbits(64)), # to protect from CSRF
"redirect_uri": CALLBACK_URL,
"response_type": "token", # note the response_type here
"scope": "email", # we want to get access to email
}
url = "?".join([AUTHORIZE_URL, urlencode(auth_params)])
webbrowser.open_new_tab(url)
redirected_url = raw_input("Paste here url you were redirected:\n")
# Note, that redirected_url will contain parameters after #
redirected_url = redirected_url.replace('oauth2?#', 'oauth2?')
redirect_params = dict(parse_qsl(urlparse(redirected_url).query))
assert redirect_params['state'] == auth_params['state'] # protect CSRF
access_token = redirect_params['access_token']
####################################
# STEP 2: request to server resource
####################################
api_params = {
'access_token': access_token,
}
url = "?".join([API_RESOURCE_URL, urlencode(api_params)])
resp = urllib2.urlopen(url)
assert resp.code == 200
resp_content = json.loads(resp.read())
email = resp_content['email']
print "Email:", email
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment