我花了很长时间让 S3 通过 PhoneGap (Cordova) FileTransfer.upload() 生成的 CORS POST 请求接受上传。任何关于我可能遗漏的建议将不胜感激。目前,我使用下面的代码收到 403 AccessDenied 响应。我已经多次与 S3 的文档进行比较,但无法找出问题所在。
这是生成签名的 Python 代码:
# Create policy document for S3.
policy_obj = {"expiration": "2014-01-01T00:00:00Z",
"conditions": [
{"bucket": "<my.bucket.name>"},
["starts-with", "$key", "story_"],
{"acl": "public-read"},
["eq", "$Content-Type", "audio/mp4"],
["content-length-range", str(0), str(2097152)]
]
}
policy = base64.b64encode(json.dumps(policy_obj))
# Create signature for S3
signature = base64.b64encode(
hmac.new(
key=app.config['AWS_SECRET_KEY'],
msg=policy,
digestmod=hashlib.sha1
).digest()
)
此过程生成的签名与S3 签名测试器生成的签名匹配(将 base64 策略转换为十六进制,然后使用密钥通过签名测试器运行)。
生成的策略和签名将传递给客户端,并且使用此 PhoneGap FileTransfer 调用构建对 S3 的请求:
// Upload file to Amazon S3
// r is the response object generated by Python
var options = new FileUploadOptions();
options.chunkedMode = false;
options.mimeType="audio/mp4";
options.fileKey='file';
options.fileName='story_' + uniqueKey + '.m4a';
options.params={
"key": "${filename}",
"acl": "public-read",
"AWSAccessKeyId": r.aws_access_key,
"Policy": r.policy,
"Signature": r.signature,
};
var ft = new FileTransfer();
ft.upload(path, "http://<my.bucket.name>.s3.amazonaws.com/", uploadSuccess, uploadFail, options);
这是 CORS 配置(是的,我计划在上传正常后将其锁定):
<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
<AllowedOrigin>*</AllowedOrigin>
<AllowedMethod>GET</AllowedMethod>
<AllowedMethod>POST</AllowedMethod>
<MaxAgeSeconds>3000</MaxAgeSeconds>
<AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>
这是存储桶策略:
{
"Version": "2008-10-17",
"Id": "Policy1356975063803",
"Statement": [
{
"Sid": "Stmt1357234455973",
"Effect": "Allow",
"Principal": {
"AWS": "*"
},
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::<my.bucket.name>/*"
},
{
"Sid": "Stmt1356975061658",
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::293855469575:root"
},
"Action": "s3:*",
"Resource": "arn:aws:s3:::<my.bucket.name>"
}
]
}
更新:
这是 Python 将对象转换为 JSON 后策略本身的样子:
{
"conditions": [
{
"bucket": "<my.bucket.name>"
},
[
"starts-with",
"$key",
"story_"
],
{
"acl": "public-read"
},
[
"eq",
"$Content-Type",
"audio/mp4"
],
[
"content-length-range",
"0",
"6291456"
]
],
"expiration": "2014-01-01T00:00:00Z"
}