boto3:generate_presigned_url在上传过程中被拒绝访问

时间:2019-04-03 16:36:58

标签: python amazon-web-services amazon-s3 boto3

我正在测试生成预签名URL,以将文件上传到S3。生成签名的URL没有任何问题,但是在尝试上传URL时出现AccessDenied错误。

我已将问题总结为以下代码进行测试。

源代码

import boto3
import os
s3 = boto3.client('s3')
def list_files():
    print("Listing files in bucket:")
    bucket = boto3.resource('s3').Bucket(bucket_name)
    for obj in bucket.objects.all():
        print(" - "+obj.key)

bucket_name = "asf-bucket"

list_files()

key= "test.py"
print (" Generating pre-signed url...")
url=s3.generate_presigned_url('put_object', Params={'Bucket':bucket_name, 'Key':key}, ExpiresIn=3600, HttpMethod='PUT')
command="curl --request PUT --upload-file {} {}".format(key, url)
print(command)
print (" Uploading with curl ...")
os.system(command)

脚本输出

$ python3 test.py
Listing files in bucket:
 - Dropped text.txt
 Generating pre-signed url...
curl --request PUT --upload-file test.py https://asf-bucket.s3.amazonaws.com/test.py?AWSAccessKeyId=----&Signature=----&Expires=----
 Uploading with curl ...
<?xml version="1.0" encoding="UTF-8"?>
<Error><Code>AccessDenied</Code><Message>Access Denied</Message><RequestId>A0E4587FFEB9F1EE</RequestId><HostId>kvfkV7YdDmtNNCSfWAjDTdZ/8+y2HrfcXSseQPlrq0300vjg9zYe1H0Qidsqf7kcBIieUGoXoUA=</HostId></Error>

使用AWS根帐户进行了测试。我遇到了同样的错误。

CORS配置

<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>GET</AllowedMethod>
    <AllowedMethod>POST</AllowedMethod>
    <AllowedMethod>PUT</AllowedMethod>
    <AllowedMethod>DELETE</AllowedMethod>
    <AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>

我缺少什么?

https://docs.aws.amazon.com/AmazonS3/latest/dev/PresignedUrlUploadObject.html

更新-添加内容类型

按照@kichik的建议,我添加了内容类型,但当前行为未更改

url=s3.generate_presigned_url('put_object', Params={'Bucket':bucket_name, 'Key':key, 'ContentType':'text/plain'}, ExpiresIn=3600, HttpMethod='PUT')
command="curl --header \"Content-Type: text/plain\" --request PUT --upload-file {} {}".format(key, url)

1 个答案:

答案 0 :(得分:0)

一切都很好,这个错误并没有在外壳上转义URL。

所以不是

curl --request PUT --upload-file test.py https://asf-bucket.s3.amazonaws.com/test.py?AWSAccessKeyId=----&Signature=----&Expires=----

curl --request PUT --upload-file test.py 'https://asf-bucket.s3.amazonaws.com/test.py?AWSAccessKeyId=----&Signature=----&Expires=----'