Skip to content

Instantly share code, notes, and snippets.

@hugotkk
Last active April 13, 2023 17:29
Show Gist options
  • Save hugotkk/bf3daf2148d9bc82303f62cb360e6401 to your computer and use it in GitHub Desktop.
Save hugotkk/bf3daf2148d9bc82303f62cb360e6401 to your computer and use it in GitHub Desktop.
Script to upload, download, and generate pre-signed URLs for files in an S3 bucket using temporary AWS credentials obtained from Cognito.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"mobileanalytics:PutEvents",
"cognito-sync:*",
"cognito-identity:*"
],
"Resource": [
"*"
]
},
{
"Effect": "Allow",
"Action": [
"s3:GetObject",
"s3:PutObject"
],
"Resource": [
"arn:aws:s3:::<bucket>/*"
]
},
{
"Effect": "Allow",
"Action": [
"s3:PutObjectAcl"
],
"Resource": [
"arn:aws:s3:::<bucket>/*"
],
"Condition": {
"StringEquals": {
"s3:x-amz-acl": "bucket-owner-full-control"
}
}
}
]
}
#!/usr/bin/env bash
# Sets the AWS region environment variable
export AWS_REGION=<region>
# Sets several environment variables that contain AWS Cognito and S3 configuration values, including client IDs, identity pool IDs, and user pool IDs
export client_id=<user_pool_app_client_id>
export client_sec=<user_pool_app_client_secret>
export identity_pool_id=<identity_pool_id>
export user_pool_id=us-east-1_tLHbqm1gS
export idp_id=cognito-idp.<region>.amazonaws.com/<user_pool_id>
# Gets an identity ID and temporary AWS credentials from Cognito using the supplied ID token
export id_token=<id_token>
export identity_id=$(aws cognito-identity get-id --identity-pool-id "${identity_pool_id}" --logins "${idp_id}=${id_token}" | jq -r .IdentityId)
export credentials=$(aws cognito-identity get-credentials-for-identity --identity-id "${identity_id}" --logins "${idp_id}=${id_token}")
export AWS_ACCESS_KEY_ID=$(echo $credentials| jq -r .Credentials.AccessKeyId)
export AWS_SECRET_ACCESS_KEY=$(echo $credentials| jq -r .Credentials.SecretKey)
export AWS_SESSION_TOKEN=$(echo $credentials| jq -r .Credentials.SessionToken)
# Uses the temporary credentials to upload a file to an S3 bucket, download the same file, and generate a pre-signed URL for the file with a one-week expiration time.
export bucket=<bucket>
export file=<file>
aws s3api put-object --bucket "${bucket}" --key "${file}" --body "${file}"
aws s3api get-object --bucket "${bucket}" --key "${file}" "${file}"
aws s3 presign s3://"${bucket}"/"${file}" --expires-in 604800
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment