问题
Is it possible to manually set the signature when making an AWS request using the AWS JavaScript SDK? I want to upload files directly to S3 but I don't want to make my keys available in plain text to the client. All the official examples require you to hardcode both your key and secret (while explicitly telling you not to do that). I'm calculating the signature server side but I haven't found a way to get that signature into the SDK.
回答1:
I ended up going a different route using AWS STS for this. However, if you do want to do something like this here is the solution:
Using the AWS JavaScript SDK they allow you to subscribe to "Request Building Events" on a AWS.Request object. These events (validate, build and sign) will allow you to access and modify request state (headers, body, etc.) before the request is sent. Most calls will return an AWS.Request instance (except .upload for S3).
Here's an example:
var request = s3.putObject({
Bucket: 'MyBucket',
Key: file.name,
ContentType: file.contentType,
Body: file
});
request.on('sign', function() {
request.httpHeaders.Authorization = 'AWS Signature';
});
request.send(function(err, data) {
// Do something here
});
I believe the trick here is to not specify a callback when creating the request (.putObject in my example) and using the .send method to initiate the request.
Documentation: http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Request.html
来源:https://stackoverflow.com/questions/28951673/set-signature-in-aws-javascript-sdk