Skip to content

Instantly share code, notes, and snippets.

@dhavaln
Last active August 17, 2021 05:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dhavaln/9093bc0fb746b34428b09c62d725c9a5 to your computer and use it in GitHub Desktop.
Save dhavaln/9093bc0fb746b34428b09c62d725c9a5 to your computer and use it in GitHub Desktop.
Generate AWS Credentials using STS to limit S3 access
const AWS = require('aws-sdk')
const STS = new AWS.STS();
const bucketName = 'appgambittest' //bucket where the data files are stored
const userId = 'user123' //userId who is requesting temporary access
const appId = 'userdir-user123' //directory name where the user data is available on s3
const roleArn = 'arn:aws:iam::XXXXXXXXXX:role/CustomS3AccessRole' //role with trust relationship and full bucket access
//generate inline session policy, with restricted access to the specific directory only
const generateInlinePolicy = (bucketName, folderName) => {
const policy = {
"Version": "2012-10-17",
"Statement": [
{
"Sid": "Stmt1",
"Effect": "Allow",
"Action": "s3:Get*",
"Resource": [
`arn:aws:s3:::${bucketName}/${folderName}/*`
]
},
{
"Sid": "Stmt2",
"Effect": "Allow",
"Action": "s3:List*",
"Resource": [
`arn:aws:s3:::${bucketName}`],
"Condition": { "StringLike": { "s3:prefix": [`${folderName}/*`] } }
}
]
}
return JSON.stringify(policy)
}
//returns temporary credentials
STS.assumeRole({
DurationSeconds: 3600, // Default 1 Hour, Maximum 12 Hours based on IAM Role configurations
ExternalId: userId,
Policy: generateInlinePolicy(bucketName, appId),
RoleArn: roleArn,
RoleSessionName: userId
}).promise()
.then(async creds => {
console.log('Temporary Credentials', creds)
// This Credentials will be configured on the Browser S3 SDK to access the files directly
const accessParam = {
accessKeyId: creds.Credentials.AccessKeyId,
secretAccessKey: creds.Credentials.SecretAccessKey,
sessionToken: creds.Credentials.SessionToken
}
return accessParam;
})
.then((creds) => {
//initiate s3 client with limited access
const S3 = new AWS.S3(creds)
//testing
const directoryToList = 'user1' //name of the directory to list files
const fileToDownload = 'user1/Page-5.png' // name of the file to download
//listing files
const listFiles = await S3.listObjects({
Bucket: bucketName,
Prefix: `${directoryToList}/`
}).promise()
console.log('List results', listFiles)
//downloading file
const getObject = await S3.getObject({
Bucket: bucketName,
Key: fileToDownload
}).promise()
console.log('Get File results', getObject)
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment