Skip to content

Instantly share code, notes, and snippets.

@durakkerem
Last active August 30, 2021 23:07
Show Gist options
  • Save durakkerem/ace8dad01f3f4dab3afce2903b117dba to your computer and use it in GitHub Desktop.
Save durakkerem/ace8dad01f3f4dab3afce2903b117dba to your computer and use it in GitHub Desktop.
Python example of AWS Cognito Authentication with username and password
"""
Username password based authentication with no SRP (secure remote password)
STEPS:
* Authorize using the /authorize endpoint and get the XSRF-TOKEN
* Use the /login endpoint to get the authentication code
* Get the access tokens using the /oauth2/token endpoint
"""
import json
import requests
import urllib
AUTH_URL = 'https://yourcognitodomain.auth.yourregion.amazoncognito.com'
REDIRECT_URI = 'https://yourredirecturi.com/'
CLIENT_ID = 'yourclientid'
SCOPE = 'openid' # Change to your scope
STATE = 'state' # optional
GRANT_TYPE = 'authorization_code'
username = 'yourusername'
password = 'yourpassword'
# Authorize and get the XSRF-TOKEN from the request cookie and response URL
url = f'{AUTH_URL}/oauth2/authorize?response_type=code&client_id={CLIENT_ID}&redirect_uri={REDIRECT_URI}&state={STATE}&scope={SCOPE}'
headers = {
'Content-Type': 'application/x-www-form-urlencoded'
}
response = requests.request("GET", url, headers=headers)
XSRF_TOKEN = response.request._cookies.get('XSRF-TOKEN', '')
print(response.url)
print(XSRF_TOKEN)
# Login to get the auth code
cookies = {
'XSRF-TOKEN': XSRF_TOKEN,
}
headers = {
}
params = (
('response_type', 'code'),
('client_id', CLIENT_ID),
('redirect_uri', REDIRECT_URI),
('state', STATE),
('scope', SCOPE),
)
data = {
'_csrf': XSRF_TOKEN,
'username': username,
'password': password,
}
response = requests.post(f'{AUTH_URL}/login', headers=headers, params=params, cookies=cookies, data=data)
code_url = urllib.parse.unquote(response.url)
code = code_url[code_url.index('code') + 5:code_url.index('&')]
print(code)
# Make a token request to get the access tokens
url = f'{AUTH_URL}/oauth2/token'
payload = f'grant_type=authorization_code&client_id={CLIENT_ID}&code={code}&redirect_uri={REDIRECT_URI}'
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Cookie': f'XSRF-TOKEN={XSRF_TOKEN}'
}
response = requests.request("POST", url, headers=headers, data=payload)
print(response.text)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment