Created
November 6, 2015 14:04
-
-
Save reinaldons/3df975a553584e9547f7 to your computer and use it in GitHub Desktop.
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
import urllib | |
import requests | |
# OAuth2 Server URL | |
URL = 'https://oauth2.server' | |
# URL to redirect after login | |
REDIRECT_URI = 'https://redirect.url' | |
# Client ID and Secret Key | |
CLIENT_ID = '' | |
CLIENT_SECRET = '' | |
# User Login | |
USER_LOGIN = '' | |
USER_PASSWORD = '' | |
def get_authorize_code(): | |
with requests.Session() as session: | |
params = { | |
'response_type': 'code', | |
'client_id': CLIENT_ID, | |
'redirect_uri': REDIRECT_URI, | |
'scope': 'email', | |
'state': 'authzcode' | |
} | |
authorize_url = ('{url}/oauth/authorize?{params}'.format(url=URL, params=urllib.urlencode(params))) | |
# This GET will redirect to /oauth/signin | |
response = session.get(authorize_url) | |
data = { | |
'msisdn': USER_LOGIN, | |
'password': USER_PASSWORD, | |
'next': authorize_url | |
} | |
# This POST will redirect to REDIRECT_URI with query ?state=authzcode&code=b9cWO85Y4vDPsh0KQaMMOTuh0sPIEU | |
response = session.post(response.url, data=data, allow_redirects=True) | |
return response.url.split('code=')[1] | |
def get_access_token(code): | |
data = { | |
'code': code, | |
'client_id': CLIENT_ID, | |
'client_secret': CLIENT_SECRET, | |
'grant_type': 'authorization_code', | |
'redirect_uri': REDIRECT_URI | |
} | |
# This POST will return a JSON with: access_token, token_type, refresh_token and scope | |
response = requests.post('{url}/oauth/token'.format(url=URL), data=data) | |
return response.json() | |
def get_user_info(token_type, access_token): | |
headers = { | |
'Authorization': '{0} {1}'.format(token_type, access_token) | |
} | |
# This POST will return a JSON with user info | |
response = requests.get('{url}/oauth/user/info'.format(url=URL), headers=headers) | |
return response.json() | |
if __name__ == '__main__': | |
""" | |
--> Authorization Request --> User Login --> User Authorization | |
<-- Authorization Grant | |
""" | |
authorize_code = get_authorize_code() | |
""" | |
--> Authorization Grant | |
<-- Access Token | |
""" | |
token = get_access_token(code=authorize_code) | |
""" | |
--> Access Token | |
<-- User Info (Protected Resource) | |
""" | |
user_info = get_user_info(token_type=token['token_type'], access_token=token['access_token']) | |
print(user_info) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment