Last active
January 18, 2022 00:25
-
-
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
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 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) |
Thanks @bjinwright and @msambol for the sample!
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
Awesome, @bjinwright.
For those running this from an EC2 instance with an instance profile, use the following to retrieve credentials: