Skip to content

Instantly share code, notes, and snippets.

@bjinwright
Last active January 18, 2022 00:25
Show Gist options
  • Save bjinwright/8c0d1e3a65017e1479d61e7dbbffb79f to your computer and use it in GitHub Desktop.
Save bjinwright/8c0d1e3a65017e1479d61e7dbbffb79f 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)
@sid88in
Copy link

sid88in commented Feb 27, 2018

Hey does this work for Cognito user pools?

@msambol
Copy link

msambol commented Dec 17, 2018

Awesome, @bjinwright.

For those running this from an EC2 instance with an instance profile, use the following to retrieve credentials:

session = boto3.Session()
credentials = session.get_credentials()

@fean
Copy link

fean commented Mar 17, 2020

Thanks @bjinwright and @msambol for the sample!

@rishabhanand26
Copy link

What if i am using SAML to Authorise my user and don't want to use the credentials, how can that happen?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment