Here's the Python code that gets temporary credentials via Cognito and uses that information to access S3. As for Python, only an incomplete implementation has been dropped, so I will post it.
On the Cognito side, give the minimum required authority to the S3 resource in advance in the non-authentication role.
Below is the code.
cognito-s3.py
client = boto3.client('cognito-identity', 'ap-northeast-1')
#Get a Cognito authentication ID on the first access
resp = client.get_id(IdentityPoolId='ap-northeast-1:<YOUR COGNITO IDENTITY POOL ID>')
print "\nIdentity ID: %s"%(resp['IdentityId'])
print "\nRequest ID: %s"%(resp['ResponseMetadata']['RequestId'])
#Get credentials to establish a Session on the second access
resp = client.get_credentials_for_identity(IdentityId=resp['IdentityId'])
secretKey = resp['Credentials']['SecretKey']
accessKey = resp['Credentials']['AccessKeyId']
token = resp['Credentials']['SessionToken']
print "\nToken: %s"%(token)
print "\nSecretKey: %s"%(secretKey)
print "\nAccessKey ID: %s"%(accessKey)
print resp
#Access S3 Object with credentials
session = Session(aws_access_key_id=accessKey,
aws_secret_access_key=secretKey,
aws_session_token=token, #Don't forget your token!
region_name='ap-northeast-1')
s3 = session.resource('s3')
obj = s3.Object(bucket_name='<BUCKET NAME>', key='<KEY NAME>')
#The following is an example of simply reading and returning the length
response = obj.get()
data = response['Body'].read()
print len(data)
Recommended Posts