Skip to content

Instantly share code, notes, and snippets.

@johnoscott
Forked from bjinwright/cognito.py
Created December 14, 2020 14:12
Show Gist options
  • Save johnoscott/98aca79afc7cf067f22db0ef3c4f4968 to your computer and use it in GitHub Desktop.
Save johnoscott/98aca79afc7cf067f22db0ef3c4f4968 to your computer and use it in GitHub Desktop.
Example of how to make an authorized call to API Gateway using Boto3, Requests, and AWS4Auth. http://stackoverflow.com/questions/37336286/how-do-i-call-an-api-gateway-with-cognito-credentials-in-python
import boto3
import datetime
import json
from requests_aws4auth import AWS4Auth
import requests
boto3.setup_default_session(region_name='us-east-1')
identity = boto3.client('cognito-identity', region_name='us-east-1')
account_id='XXXXXXXXXXXXXXX'
identity_pool_id='us-east-1:YYY-YYYY-YYY-YY'
api_prefix='ZZZZZZZZZ'
response = identity.get_id(AccountId=account_id, IdentityPoolId=identity_pool_id)
identity_id = response['IdentityId']
print ("Identity ID: %s"%identity_id)
resp = identity.get_credentials_for_identity(IdentityId=identity_id)
secretKey = resp['Credentials']['SecretKey']
accessKey = resp['Credentials']['AccessKeyId']
sessionToken = resp['Credentials']['SessionToken']
expiration = resp['Credentials']['Expiration']
print ("\nSecret Key: %s"%(secretKey))
print ("\nAccess Key %s"%(accessKey))
print ("\nSession Token: %s"%(sessionToken))
print ("\nExpiration: %s"%(expiration))
method = 'GET'
headers = {}
body = ''
service = 'execute-api'
url = 'https://%s.execute-api.us-east-1.amazonaws.com/dev/helloworld' % api_prefix
region = 'us-east-1'
auth = AWS4Auth(accessKey, secretKey, region, service, session_token=sessionToken)
response = requests.request(method, url, auth=auth, data=body, headers=headers)
print(response.text)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment