How to Generate Presigned URL from S3 Bucket using AngularJS
Posted By : Vishal Kumar | 23-Aug-2017
When we are storing the objects in S3 buckets like images, pdfs and other documets and the objects are private not public, then we can not access these objects directly using url. If objects are public then we can directly hit the S3 url for accessing them but here we need to generate a presigned url for accessing these objects. Below are the steps of generating presigned url using angularjs or javascript.
Step 1: First of all we need to install aws-sdk-js in our project
bower install aws-sdk-js
Step 2: Now we need to perform authentication using our accesskey and secret
AWS.config = {
accessKeyId: "xxxxxxxxxxxxxxxxx",
secretAccessKey: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
}
Step 3: Now we have configured the AWS with accesskey and secret. So we can get the object of S3 with the help of this AWS easily.
var s3 = new AWS.S3();
Step 4: Now we have to tell S3 the name of our bucket, expiry time of generated url and key that is our object that we want to access.
s3.getSignedUrl('getObject'{
Bucket: 'your bucket name',
Expires: 60 * 60, //This means that url valid for 1 hour
Key: 'profile-image/xxxxxxxxxx.jpg' //profile-image is the folder name that is already created in the bucket
}, function(err, url){
if(err) {
console.log(err);
}
else {
var profileImage = url;
}
}
So generated presigned url looks somthing like below url. If you tried to hit this url in the browser it would open your image or download your image without any problem.
https://s3.amazonaws.com/#{S3_BUCKET}/#{path}?AWSAccessKeyId=#{S3_ACCESS_KEY_ID}&Expires=#{expire_date}&Signature=#{signature}
Conclusion: In the generated presigned url you can see that there are some extra values appended by S3. These are accesskey, expiry and a signature that you are not sending to S3 anywhere. when you call the function getSignedUrl() of S3 it generate a nonce using your secret (that is used for authentication) and then generate a signature with the help of this nonce. These new values nonce and signature are valid only for limited time(that you are sending in Expires).
Note: If you are uploding objects public in your S3 bucket then these objects can be accessed by anyone(If that person know the url).
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Vishal Kumar
Vishal Kumar is Master in Computers Application. He has good technical skills in Java and always motivated to learn new things.