Get a non-public JavaScript file from AWS S3 using your API

I am trying to follow AWS API to get JavaScript file from S3 private bucket. The tutorial is here: Signing and validating REST requests

The environment is a browser with jQuery, so it is a JavaScript implementation. I worked through what I thought was tricky - signing the request with a secret key. But now I have hung up on something that was easy. I have this REST request to submit:

GET /gss3/sayHello.js HTTP/1.1
Host: gss3.s3.amazonaws.com
Date: Thu Feb 07 2013 08:16:25 GMT-0500 (Eastern Standard Time)
Authorization: AWS AKIAJTURNBE6SXNTVVGQ:eWJOLZnj6Eja3CEC2CyifeURnxg=

      

Since this is a call to s3.amazonaws.com from www.mydomain.com I looked at JSONP to get around the same origin policy. However, I see no way to add extra headers to the jQuery JSONP call, and to authenticate with AWS you have to pass this 4th line:

Authorization: AWS AKIAJTURNBE6SXNTVVGQ:eWJOLZnj6Eja3CEC2CyifeURnxg=

      

So my question is this: how do I pass this AWS REST request in my browser / jQuery environment? What am I missing here? Thanks gang ....

+3


source to share


2 answers


Although this source was written for PHP, the Amazon AWS S3 Query String Authentication with PHP blog shows how to compile a simple old query and pass the signature as a parameter to S3.

$url .= '?AWSAccessKeyId='.$awsKeyId
.'&Expires='.$expires
.'&Signature='.$signature;

      

Using crypto-js and switching to Javascript, we will give us something like this:



var filePath = "/bucket/file.js";
var dateTime = Math.floor(new Date().getTime() / 1000) + 300; // allows for 5 minutes clock diff
var stringToSign = "GET\n\n\n" + dateTime + "\n" + filePath;
var signature = CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA1(stringToSign, secretAccessKey));
var queryString = "?AWSAccessKeyId=" + accessKeyId + "&Expires=" + dateTime + "&Signature=" + encodeURIComponent(signature);

var script = document.createElement("script");
script.type = "text/javascript";
script.src = "https://s3.amazonaws.com/bucket/file.js" + queryString;
$("head").append(script); // jQuery version

      

And here you are, almost all of the banana is written for you. Hope this helps someone.

+4


source


You cannot add headers to a JSON-P call, as a JSON-P call is just a dynamic tag added to your web page, unless S3 supports passing it as a GET parameter.

If you are using JSON-P, the cross-domain question issue no longer matters. As long as its valid JS can be pulled to your webpage from any domain. You just need to make sure the S3 file has permission to be viewed by any user.



The last way to do this is to enable the S3 bucket with CORS (cross domain ajax), which is a new feature in S3. Then you can do vanilla ajax, name the cross domain to your s3 bucket, and add additional headers to your hearts content.

0


source







All Articles